How to validate iranian Melli Code (National Code or Code Melli) in android

前端 未结 7 1389
花落未央
花落未央 2021-02-19 09:25

I need a method to validate the Melli Code (National Code or Code Melli) of iranian people.

I Know it has a formula.

7条回答
  •  遇见更好的自我
    2021-02-19 10:00

    Good job Alireza, Here is my code which is very similar to yours.

    ‍‍‍

    private boolean isValidNationalCode(String nationalCode) {
        if (nationalCode.length() != 10) {
          return false;
        } else {
          //Check for equal numbers
          String[] allDigitEqual = {"0000000000", "1111111111", "2222222222", "3333333333",
              "4444444444", "5555555555", "6666666666", "7777777777", "8888888888", "9999999999"};
          if (Arrays.asList(allDigitEqual).contains(nationalCode)) {
            return false;
          } else {
            int sum = 0;
            int lenght = 10;
            for (int i = 0; i < lenght - 1; i++) {
              sum += Integer.parseInt(String.valueOf(nationalCode.charAt(i))) * (lenght - i);
            }
    
            int r = Integer.parseInt(String.valueOf(nationalCode.charAt(9)));
    
            int c = sum % 11;
    
            return (((c < 2) && (r == c)) || ((c >= 2) && ((11 - c) == r)));
          }
    
        }
      }
    

提交回复
热议问题