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:

AB123456C

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():

<html>
<head>
<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.";

}
else
{

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

}
}

</script>

<style type="text/css">
<!--
body {
background:#CCCCFF;
}

div {
width: 100%;
text-align: center;
margin-top:150px;
}

span {
color: #000099;
font: 8pt verdana;
font-weight:bold;
text-decoration:none;
}

input {
color: #000000;
background: #F8F8F8;
border: 1px solid #353535;
width:250px;
font: 8pt verdana;
font-weight:normal;
text-decoration:none;
margin-top:5px;
}
-->
</style>
</head>
<body>

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

</body>
</html>


Login
Want to leave a comment?

No problem. Just enter your email and password below.


register | home | reminder

myDesignTool Networking • www.mydesigntool.cominfo@mydesigntool.com