Skip to content

Instantly share code, notes, and snippets.

@henhan
Last active April 7, 2016 06:12
Show Gist options
  • Save henhan/90b282963f4491c7a45ae479b85e6db0 to your computer and use it in GitHub Desktop.
Save henhan/90b282963f4491c7a45ae479b85e6db0 to your computer and use it in GitHub Desktop.
Robust validation of Swedish personal ID in java
import java.util.Calendar;
public class SwedishIdUtils {
public static boolean validateId(String id) {
// Only allow digits, whitespace + and - (+ is sometimes used to indicate age greater than 100 years)
if (id == null || !id.matches("^[\\-\\s\\+\\d]+$")) {
return false;
}
// Remove all non digits
String in = id.replaceAll("\\D", "");
if (in.length() != 10 && in.length() != 12) {
return false;
}
if (in.length() == 12) {
// Validate century prefix and reduce string that is to be validated to 10 digits
// Other prefixes than these indicate that it is a company
int prefix = Integer.parseInt(in.substring(0, 2));
if (prefix < 18 || prefix > 20) {
return false;
}
// Validate that year is not greater than current
int currentYear = Calendar.getInstance().get(Calendar.YEAR);
if (Integer.parseInt(in.substring(0, 4)) > currentYear) {
return false;
}
in = in.substring(2);
}
int sum = 0;
for (int i = 0; i < in.length(); i++) {
int value = Character.getNumericValue(in.charAt(i));
sum += getValidationValue(i, value);
}
return sum % 10 == 0;
}
private static int getValidationValue(int index, int baseValue) {
if (index % 2 != 0) {
return baseValue;
}
int doubled = 2 * baseValue;
if (doubled < 10) {
return doubled;
} else {
return 1 + (doubled - 10);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment