Search code examples
validationfluttermethodsdart

How to check and validate Iranian National Code (Melli Code) in Flutter?


How to validate Iranian 10 digits national code in Flutter (Dart)?

It has a specific pattern.


Solution

  • Following method is written in Dart based on this android code and is tested to validate Iranian National Code (Melli-Code) in Flutter:

     bool validateNationalCode(String nc) {
        if (nc.trim() == '') {
          return false;
        } else if (nc.length != 10) {
          return false;
        } else {
          int sum = 0;
    
          for (int i = 0; i < 9; i++) {
            sum += int.parse(nc[i]) * (10 - i);
          }
    
          int lastDigit;
          int divideRemaining = sum % 11;
    
          if (divideRemaining < 2) {
            lastDigit = divideRemaining;
          } else {
            lastDigit = 11 - (divideRemaining);
          }
    
          if (int.parse(nc[9]) == lastDigit) {
            return true;
          } else {
            return false;
          }
        }
      }