I'm in the middle of trying to validate a UK national Insurance no. as part of a form. Obviously it needs validating server-side as well, but I'm using the new :valid
:invalid
CSS pseudo-styles to give the user instant feedback on the form.
<input type="text" required="required" pattern="Foo"/>
I'm not fluent in Regular Expressions at all. Would anyone kindly be able to solve the riddle and create a RegEx for myself and others to use inside the pattern="#"
attribute?
If it helps, someone has already roughly answered this question before: Regular Expression to validate UK National Insurance Number. However, upon testing, none of the answers seemed to work at all.
The format of the number is two prefix letters, six digits, and one suffix letter.
The example typically used is AB123456C
.
Often, the number is printed with spaces to pair off the digits, like this: AB 12 34 56 C
.
D
, F
, I
, Q
, U
or V
. The second letter also cannot be O
.BG
, GB
, NK
, KN
, TN
, NT
and ZZ
are not allocated.A
, B
, C
or D
.This one should suit your needs:
^(?!BG|GB|NK|KN|TN|NT|ZZ)[A-CEGHJ-PR-TW-Z][A-CEGHJ-NPR-TW-Z](?:\s*\d{2}){3}\s*[A-D]$
Visualization by Debuggex
Demo:
var regex = /^(?!BG|GB|NK|KN|TN|NT|ZZ)[A-CEGHJ-PR-TW-Z][A-CEGHJ-NPR-TW-Z](?:\s*\d{2}){3}\s*[A-D]$/;
var input = document.querySelector("input");
var span = document.querySelector("span");
input.addEventListener("input", function (event) {
span.innerHTML = regex.test(event.target.value) ? "✔" : "✗";
}, false);
<input type="text" placeholder="Ex: AB 12 34 56 D" /> <span></span>
Using the latest list provided by NEST the REGEX should be (assuming no spaces)
R = new Regex("
(^[AEHKLTYZ]{1}[ABEHK-MPR-TW-Z}{1}
|^[B]{1}[ABEK-MT]{1}
|^[C]{1}[ABEHKLR]{1}
|^[G]{1}[Y]{1}
|^[J]{1}[A-CEGHJ-NPR-TW-Z]{1}
|^[M]{1}[AWX]{1}
|^[N]{1}[ABEHLMPRSW-Z]{1]
|^[O]{1}[ABEHK-MPRSX]{1}
|^[P]{1}[A-CEGHJ-NPR-TW-Y]{1}
|^[R]{1}[ABEHKMPR-TW-Z]{1}
|^[S]{1}[A-CEGHJ-NPR-TW-Z]{1}
|^[W]{1}[ABEK-MP]{1})[0-9]{6}[A-DFM]{1}$");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With