Skip to content

Instantly share code, notes, and snippets.

@johanstenberg92
Last active December 21, 2015 01:59
Show Gist options
  • Save johanstenberg92/6231799 to your computer and use it in GitHub Desktop.
Save johanstenberg92/6231799 to your computer and use it in GitHub Desktop.
Validates a swedish social security number
/**
* Validates a Swedish social security number.
*
* @author Johan Stenberg
*/
public class SSNValidatorUtils extends AbstractUtils {
private SSNValidatorUtils() {
}
public static boolean validateSSN(String ssn) {
if (ssn == null || ssn.length() != 13 || ssn.indexOf('-') != 8) {
return false;
}
String pattern = "^[12][90][0-9]{6}-[0-9]{4}";
if (!ssn.matches(pattern)) {
return false;
}
int year = Integer.parseInt(ssn.substring(0, 4));
int month = Integer.parseInt(ssn.substring(4, 6));
int day = Integer.parseInt(ssn.substring(6, 8));
boolean validMonthAndDate = validateMonthAndDate(month, day, isLeapYear(year));
if (!validMonthAndDate) {
return false;
}
int checkSumDigit = Integer.parseInt(ssn.substring(ssn.length() - 1, ssn.length()));
String ssnModifiedForCheckSum = ssn.substring(2, 8) + ssn.substring(9, ssn.length() - 1);
return validCheckSum(ssnModifiedForCheckSum, checkSumDigit);
}
private static boolean validateMonthAndDate(int month, int day, boolean isLeapYear) {
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return day >= 1 && day <= 31;
case 4:
case 6:
case 9:
case 11:
return day >= 1 && day <= 30;
case 2:
return day >= 1 && day <= (isLeapYear ? 29 : 28);
default:
return false;
}
}
private static boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
private static boolean validCheckSum(String ssnModifiedForCheckSum, int checkSumDigit) {
int sum = 0;
for (int i = 0; i < ssnModifiedForCheckSum.length(); ++i) {
int j = Character.getNumericValue(ssnModifiedForCheckSum.charAt(i));
j *= (i % 2 == 0) ? 2 : 1;
sum += j - (j > 9 ? 9 : 0);
}
int calcedCheckSum = 10 - (sum % 10);
return (calcedCheckSum == 10 ? 0 : calcedCheckSum) == checkSumDigit;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment