How to validate Social Security Number (SSN) using JavaScript Regular Expressions

When I wrote the JS regular expression article last week I had no idea that it will attract so many visitors. Not only did so many people read this post, many more visited my blog searching for other regular expressions. So I decided to write few more posts about JavaScript regular expressions and how to use them to validate Social Security number, zip code, phone number and numeric data. I’ll divide these into smaller posts discussing one regular expression per post to keep it simple for the readers.

In today’s post I’ll show you how to use JavaScript regular expression to validate Social Security number. Let me first show you the JS code.

 
    function validateSSN (elementValue){
       var  ssnPattern = /^[0-9]{3}\-?[0-9]{2}\-?[0-9]{4}$/;
       return ssnPattern.test(elementValue);
   }

Explanation:

The argument to this method is the social security number you want to validate.

In the method body we define a variable (‘ssnPattern’) and assign a regular expression to it.

SNN format: The regular expression for social security number (SSN) is

/^[0-9]{3}\-?[0-9]{2}\-?[0-9]{4}$/

To understand the regular expression we will divide it into smaller components:

/^[0-9]{3}:  Means that the social security number must begin with at least three numeric characters.

\-?:   Means that SSN can have an optional hyphen (-) after first 3 digits.

[0-9]{2}: First 3 digits (or optional hyphen) must be followed by 2 more digits.

\-?: After the second group of digits there may be another optional hyphen (-) character.

[0-9]{4}$/: Finally, the social security number must end with four digits.

 

On the final line we call test method for our regular expression and pass the social security number as input. If the input SSN satisfies our regular expression, ‘test’ will return true otherwise it will return false. We return this value to the calling method.

You can call this method whenever you want to validate social security number.

Examples:

Following SSNs will pass validation : 345-90-98023, 234908908; 239-586767; 73467-8790

The method will return false for following SSNs. 34-909-9098; 34a-20-7678;