Java Regular Expression to Validate Social Security Number (SSN)
Here is a utility method to check if a given String is a valid Social Security number using Java Regular Expression.
/** isSSNValid: Validate Social Security number (SSN) using Java regex.
* This method checks if the input string is a valid SSN.
* @param email String. Social Security number to validate
* @return boolean: true if social security number is valid, false otherwise.
*/
public static boolean isSSNValid(String ssn){
boolean isValid = false;
/*SSN format xxx-xx-xxxx, xxxxxxxxx, xxx-xxxxxx; xxxxx-xxxx:
^\\d{3}: Starts with three numeric digits.
[- ]?: Followed by an optional "-"
\\d{2}: Two numeric digits after the optional "-"
[- ]?: May contain an optional second "-" character.
\\d{4}: ends with four numeric digits.
Examples: 879-89-8989; 869878789 etc.
*/
//Initialize regex for SSN.
String expression = "^\\d{3}[- ]?\\d{2}[- ]?\\d{4}$";
CharSequence inputStr = ssn;
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(inputStr);
if(matcher.matches()){
isValid = true;
}
return isValid;
}
This method will return true if the given String matches one of these SSN formats xxx-xx-xxxx, xxxxxxxxx, xxx-xxxxxx, xxxxx-xxxx:
Social Security RegEx Explained:
A String would be considered a valid Social Security Number (SSN) if it satisfies the following conditions:
^\\d{3}: Starts with three numeric digits.
[- ]?: Followed by an optional “-“
\\d{2}: Two numeric digits after the optional “-“
[- ]?: May contain an optional second “-” character.
\\d{4}: ends with four numeric digits.