User Tools

Site Tools


js:jquery_validate_cnp

Validate a CNP (Romanian Personal Numeric Code)

19.02.2010

We're using validation jquery plugin.
To check a CNP, add a new method like this:

    $.validator.addMethod(
        "roCNP",
        function(value, element) {
            var check = false;
            var re = /^\d{1}\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])(0[1-9]|[1-4]\d| 5[0-2]|99)\d{4}$/;
            if( re.test(value)) {
                var bigSum = 0, rest = 0, ctrlDigit = 0;
                var control = '279146358279';
                for (var i = 0; i < 12; i++) {
                    bigSum += value[i] * control[i];
                }
                ctrlDigit = bigSum % 11;
                if ( ctrlDigit == 10 ) ctrlDigit = 1;
 
                if ( ctrlDigit != value[12] ) return false;
                else return true;
            } return false;
        }, 
        "CNP invalid"
    );

And check it like this:

    $("#form_id").validate({ 
        rules: { 
             cnp: { required: true, roCNP: true }
        },
        messages: { 
             cnp: "Your custom error message", 
        }
    });

References:

Details about CNP
A lot more regex on this subject

js/jquery_validate_cnp.txt · Last modified: 2013/03/16 17:40 (external edit)