Search code examples
javaandroidnumbers

Turkish Identity Number Verification


How can I make sure that the given text is Turkish Identity Number? I have seen js version here and phthon version here

Also, posted a question couple of days ago for swift version here.

Turkish Identity Verification is not checks only if its numeric, it has some other functions too. Let me be more clear, It is numeric and has 11 digits. For example Let assume that first 9 digits are represented by d, and the last ones represented by c:

Identity Number = d1 d2 d3 d4 d5 d6 d7 d8 d9 c1 c2

10th digit must be,

c1 = ( (d1 + d3 + d5 + d7 + d9) * 7 - (d2 + d4 + d6 + d8) ) mod10

11th must be,

c2 = ( d1 + d2 + d3 + d4 + d5 + d6 + d7 + d8 + d9 + c1 ) mod10

and it never starts with "0". For example, "87836910956" is a Turkish Identity Number.

Now I have to use this validation in android/java.


Solution

  • You could shorten it a little bit without losing readability to:

    private static boolean verifyNumber(String nationalityNumberStr) {
        if(nationalityNumberStr.startsWith("0") || !nationalityNumberStr.matches("[0-9]{11}") ){
            return false;
        }
    
        int [] temp = new int [11];
        for (int i = 0; i < 11; i++){
            temp[i] = Character.getNumericValue(nationalityNumberStr.toCharArray()[i]);
        }
    
        int c1 = 0;
        int c2 = temp[9];
        for(int j = 0; j < 9; j++){
            if(j%2 == 0) {
               c1 += temp[j] * 7;
            }
            else {
               c1 -=  temp[j];
            }
            c2 += temp[j];
        }
    
        return  temp[9]== c1 % 10 && temp[10] == c2 %10;
    }