Last active
April 7, 2016 06:12
Revisions
-
henhan revised this gist
Apr 7, 2016 . 1 changed file with 1 addition and 1 deletion.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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 == null || !id.matches("^[\\-\\s\\+\\d]+$")) { return false; } // Remove all non digits -
henhan created this gist
Apr 6, 2016 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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); } } }