Reputation: 14774
I am trying to use some RegEx in JS to validate a National Insurance number.
^(?i:[a-z-[dfiquv]])(?i:[a-z-[dfiquvo]])\d{6}(?i:a|b|c|d)$
This is taken from a language that is not JS, but how can I use this rule in JS?
I assume I should be escaping some characters here.
Thanks!
Upvotes: 1
Views: 2037
Reputation: 75
I needed to validate UK National Insurance numbers on a large scale and came across this post. However, I found using regex to validate was really slow. So I created this npm package which doesn't use regex and is roughly 14 x faster: test-nino. Just thought I would share incase anyone else needs a higher performance solution.
Upvotes: 0
Reputation: 89557
Your pattern is equivalent to this:
/^[abceghj-prstw-z][abceghj-nprstw-z]\d{6}[abcd]$/i
the original pattern doesn't work in javascript for this reason:
character class substraction is not supported by XRegExp (the javascript regex engine). So, [a-z-[dfiquv]]
will be seen as:
[a-z-[dfiquv] # a character class that contains:
# the character range a-z
# -
# [
# the (duplicate) letters: dfiquv
] # followed by a literal ]
An other notice about the original pattern: XRegExp doesn't support the inline modifier in a non capturing group syntax: (?i:......)
(that is a shortcut for (?:(?i)......)
, note that javascript doesn't support (?i)
too, it doesn't support inline modifiers at all). Since all the pattern seems to be case insensitive, the best way is to put the modifier for all the pattern like this: /... pattern .../i
and remove the uneeded non-capturing groups.
Upvotes: 3
Reputation: 785058
This is fairly close to a JS compatible regex, just with minor changes try this:
/^(:[a-z][dfiquv])(:[a-z][dfiquvo])\d{6}(:[abcd])$/i
Upvotes: 1