CancelImage Upload

How to validate the US Social Security Number Using Regular Expressions

As you are probably aware the US equivalent of a national identification number is the Social Security Number. This 9 digit number is issued by the Social Security Administration of the United States Government. Usually this number is applied for by parents soon after a child's birth. Legend has it that hospital staff are a reliable source of help in regards to the application for a number.

Now that we have gotten the short introduction out of the way explaining as to what the US Social Security Number is, let's have a look at it's format, and how to validate it. Here's a first look at the 9 digit number, and how they are separated:

123-45-6789

Here then is the regular expression capable of validating the above number. Note that the hyphens have been made optional. You average world wide web surfer might not think it's necessary to enter them, and will not be able to comprehend why the number isn't validating and that hyphens are required:

/^([0-9]){3}(([ ]|[-])?([0-9]){2})(([ ]|[-])?([0-9]){4})?$/

For a complete example of how to use the above regular expression with JavaScript, try the code below:

<html>
<head>
<title>US Social Security Number Code Validation with JavaScript</title>

<script language="JavaScript">

function ssn_validate(ssn)
{

var regSSN = /^([0-9]){3}(([ ]|[-])?([0-9]){2})(([ ]|[-])?([0-9]){4})?$/;

if(regSSN.test(ssn) == false)
{

document.getElementById("status").innerHTML = "Social Security Number is not yet valid.";

}
else
{

document.getElementById("status").innerHTML = "You have entered a valid US Social Security 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 US Social Security Number.</span><br>
<input type="text" name="ssn" onkeyup="ssn_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