A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://howtodoinjava.com/java/regex/java-regex-validate-social-security-numbers-ssn/ below:

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 following rules.

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 !!


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4