Regex to Validate SSN (Social Security Number)

In this Java regex tutorial, we will learn to use regular expressions to test whether a user has entered a valid Social Security number in your application or website form. 1. Valid SSN Pattern United States Social Security numbers are nine-digit numbers in the format AAA-GG-SSSS with the …

In this Java regex tutorial, we will learn to use regular expressions to test whether a user has entered a valid Social Security number in your application or website form.

1. Valid SSN Pattern

United States Social Security numbers are nine-digit numbers in the format AAA-GG-SSSS with the following rules.

  • The first three digits are called the area number. The area number cannot be 000, 666, or between 900 and 999.
  • Digits four and five are called the group number and range from 01 to 99.
  • The last four digits are serial numbers from 0001 to 9999.

To validate all the above 3 rules, our regex would be:

Regex : ^(?!000|666)[0-8][0-9]{2}-(?!00)[0-9]{2}-(?!0000)[0-9]{4}$

2. Explanation of Regex

^            # Assert position at the beginning of the string.
(?!000|666)  # Assert that neither "000" nor "666" can be matched here.
[0-8]        # Match a digit between 0 and 8.
[0-9]{2}     # Match a digit, exactly two times.
-            # Match a literal "-".
(?!00)       # Assert that "00" cannot be matched here.
[0-9]{2}     # Match a digit, exactly two times.
-            # Match a literal "-".
(?!0000)     # Assert that "0000" cannot be matched here.
[0-9]{4}     # Match a digit, exactly four times.
$            # Assert position at the end of the string.

3. Demo

Now let’s test our SSN validation regex using some demo SSNs.

List<String> ssns = new ArrayList<String>();
       
//Valid SSNs
ssns.add("123-45-6789");  
ssns.add("856-45-6789");  
 
//Invalid SSNs
ssns.add("000-45-6789");  
ssns.add("666-45-6789");  
ssns.add("901-45-6789");  
ssns.add("85-345-6789"); 
ssns.add("856-453-6789"); 
ssns.add("856-45-67891"); 
ssns.add("856-456789"); 
 
String regex = "^(?!000|666)[0-8][0-9]{2}-(?!00)[0-9]{2}-(?!0000)[0-9]{4}$";
 
Pattern pattern = Pattern.compile(regex);
 
for (String number : ssns)
{
  Matcher matcher = pattern.matcher(number);
  System.out.println(matcher.matches());
}

The program output:

true
true
 
false
false
false
false
false
false
false

I will advise to play with above simple regular expression to try more variation.

Happy Learning !!

Weekly Newsletter

Stay Up-to-Date with Our Weekly Updates. Right into Your Inbox.

Comments

Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.