Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use regex to validate a UK National Insurance No./NINO in an HTML5 pattern attribute

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.

A Little UK National Insurance No. Information

Format

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.

Rules of the Road

  • Neither of the first two letters can be D, F, I, Q, U or V. The second letter also cannot be O.
  • The prefixes BG, GB, NK, KN, TN, NT and ZZ are not allocated.
  • The suffix letter is either A, B, C or D.
like image 872
Adam Ross Bowers Avatar asked Sep 03 '25 05:09

Adam Ross Bowers


2 Answers

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]$

Regular expression visualization

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>
like image 198
sp00m Avatar answered Sep 04 '25 22:09

sp00m


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}$");
like image 40
Ewan Avatar answered Sep 04 '25 21:09

Ewan