Skip to content

Instantly share code, notes, and snippets.

@wernsey
Last active April 17, 2019 12:35
Show Gist options
  • Save wernsey/a18395f9256ca975685b9ea4844342ed to your computer and use it in GitHub Desktop.
Save wernsey/a18395f9256ca975685b9ea4844342ed to your computer and use it in GitHub Desktop.
Validates a South African ID number
/**
* Validates a South African ID number
*
* See http://geekswithblogs.net/willemf/archive/2005/10/30/58561.aspx and
* https://www.westerncape.gov.za/general-publication/decoding-your-south-african-id-number-0
*
* @param id
* @return
*/
public static boolean validId(String id) {
Matcher m = ID_PATTERN.matcher(id);
if(!m.find())
return false;
int yy = Integer.parseInt(m.group(1));
int mm = Integer.parseInt(m.group(2));
int dd = Integer.parseInt(m.group(3));
int g = Integer.parseInt(m.group(4));
int s = Integer.parseInt(m.group(5));
int c = Integer.parseInt(m.group(6));
int a = Integer.parseInt(m.group(7));
int z = Integer.parseInt(m.group(8));
if(mm < 1 || mm > 12 || dd < 1 || dd > 31) return false;
char [] cs = id.toCharArray();
int s1 = (cs[0] - '0') + (cs[2] - '0') + (cs[4] - '0') + (cs[6] - '0') + (cs[8] - '0') + (cs[10] - '0');
int s2 = Integer.parseInt("" + cs[1] + cs[3] + cs[5] + cs[7] + cs[9] + cs[11]);
s2 *= 2;
char [] cx = Integer.toString(s2).toCharArray();
s2 = 0;
for(char cc : cx)
s2 += cc - '0';
s2 += s1;
String st = Integer.toString(s2);
s2 = st.charAt(st.length() - 1) - '0';
if(10 - s2 != z) return false;
// System.out.println(yy + "-" + mm + "-" + dd + " " + (g >= 5 ? 'M' : 'F') + " " + s + " " + (c == 0 ? "citizen" : "other") + " " + a + " " + z );
return true;
}
private static final Pattern ID_PATTERN = Pattern.compile("^(\\d{2})(\\d{2})(\\d{2})(\\d)(\\d{3})([01])(\\d)(\\d)$");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment