angular.js nin--input validate
علی ذوالفقار
1399/09/23 10:56:55 (28)
// add a custom directive to validate nin -> nin_validate
app.directive('ninValidate', function() {
    return {      
      require: 'ngModel', // $validators does not work if ngModel not set       
      link: function(scope, elm, attrs, ctrl) {
        //   console.log(ctrl.$validators)
        ctrl.$validators.ninValidate = function(modelValue, viewValue) { // add a validator to control.$validators (return true/false)
            return validate_nin(viewValue) ; // use validate_nin function as validator logic ;)
        };
      } 
    };
});

function validate_nin(nin) {
    // console.log('validate nin : ' , nin ) ; 
    if (!nin || nin.length < 10) { 
        return false; // if nin length is less than 10 character , nin is wrong 
    } else {
        // check for valid pattern
        if (nin == '0000000000' || nin == '1111111111' || nin == '2222222222' || nin == '3333333333' || nin == '4444444444' || nin == '5555555555' || nin == '6666666666' || nin == '7777777777' || nin == '8888888888' || nin == '9999999999') {
            return false; // wrong nin
        } else {
            // check for parity with refahi.ir check function
            var c = parseInt(nin.charAt(9));
            var n = parseInt(nin.charAt(0)) * 10 +
                parseInt(nin.charAt(1)) * 9 +
                parseInt(nin.charAt(2)) * 8 +
                parseInt(nin.charAt(3)) * 7 +
                parseInt(nin.charAt(4)) * 6 +
                parseInt(nin.charAt(5)) * 5 +
                parseInt(nin.charAt(6)) * 4 +
                parseInt(nin.charAt(7)) * 3 +
                parseInt(nin.charAt(8)) * 2;
            var r = n - parseInt(n / 11) * 11;
            //             return (r == 0 && r == c) || (r == 1 && c == 1) || (r > 1 && c == 11 - r);
            if ((r == 0 && r == c) || (r == 1 && c == 1) || (r > 1 && c == 11 - r)) {
                return true;
            } else {
                return false
            }
        }
    }
}; 
Back