CancelImage Upload

Validating the British National Insurance Number with Regular Expressions

The following page discusses how regular expressions can be used to validate the British National Insurance Number, which is allocated to ever UK resident within the United Kingdome upon their 16th birthday. This number is usually received in a card format, containing a 9 digit code, consisting of the following format, 2 letters, 6 numbers and then to finish another letter:

AB 12 34 56 C

In our regular expression we will not only have to bear the combination of letters and numbers in mind, but also the above displayed gapping between the characters, with which the numbers could be entered into a textbox. We will therefore have to allow for the above example as well as:


Here then is what the regular expression code would look like based on those two criteria. Note the optional spacing between the symbols with ()?, and the exactly specified number of repetitions for the rest.:

/^([a-zA-Z]){2}( )?([0-9]){2}( )?([0-9]){2}( )?([0-9]){2}( )?([a-zA-Z]){1}?$/

Here is a more extensive JavaScript example where the code is entered into a textbox, and then validated inside a function named ni_validate():

<title>National Insurance Number Validation with JavaScript</title>

<script language="JavaScript">

function ni_validate(niNumber)

var regNI = /^([a-zA-Z]){2}( )?([0-9]){2}( )?([0-9]){2}( )?([0-9]){2}( )?([a-zA-Z]){1}?$/;

if(regNI.test(niNumber) == false)

document.getElementById("status").innerHTML = "National Insurance Number is not yet valid.";


document.getElementById("status").innerHTML = "You have entered a valid National Insurance Number!";



<style type="text/css">
body {

div {
width: 100%;
text-align: center;

span {
color: #000099;
font: 8pt verdana;

input {
color: #000000;
background: #F8F8F8;
border: 1px solid #353535;
font: 8pt verdana;

<span id="status">Please enter a valid National Insurance Number.</span><br>
<input type="text" name="ni_number" onkeyup="ni_validate(this.value);">


Want to leave a comment?

No problem. Just enter your email and password below.

register | home | reminder

myDesignTool Networking •