Skip to content

Instantly share code, notes, and snippets.

@henhan
Last active April 7, 2016 06:12

Revisions

  1. henhan revised this gist Apr 7, 2016. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion SwedishIdUtils.java
    Original file line number Diff line number Diff line change
    @@ -4,7 +4,7 @@ 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.matches("^[\\-\\s\\+\\d]+$")) {
    if (id == null || !id.matches("^[\\-\\s\\+\\d]+$")) {
    return false;
    }
    // Remove all non digits
  2. henhan created this gist Apr 6, 2016.
    49 changes: 49 additions & 0 deletions SwedishIdUtils.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,49 @@
    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.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);
    }
    }

    }