This handy method using Java validates if a U.S. social security number represented as a String is valid or not. Some format examples can either be 879-89-8989 or 869878789 and many others. This method uses a REGEX expression for validation with the following details:
^\\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.
Check the code below.
|
1 2 3 4 5 6 7 8 9 10 11 |
public static boolean isSSNValid(String ssn) { boolean isValid = false; 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; } |