0
votes

I used jquery validation plugin to validate my form but in one text box I want to validate the NIC(National Identity Card) number of our country .I got the regular expression for NIC number can anyone tell me how to add additional method to validate this .

reqular expression for NIC number : /^[0-9]{9}[vVxX]$/ textbox id : showNic

here is my jQuery code...

$(document).ready(function () {
    jQuery.validator.setDefaults({
        // where to display the error relative to the element
        errorPlacement: function (error, element) {
            error.appendTo(element.parent().find('div.myErrors'));
        }
    });
    $('#basicDetails').validate({ // initialize the Plugin
        rules: {
            fname: {
                required: true,
                lettersonly: true,
            },
            lname: {
                required: true,
                lettersonly: true,
            },
        },
        messages: {
            fname: {
                required: "Please enter your first name",
                lettersonly: "Login format not valid",
            },
            lname: {
                required: "Please enter your last name",
                lettersonly: "Login format not valid",
            },
        },
        submitHandler: function (form) { // for demo
            alert('valid form submitted'); // for demo
            return false; // for demo
        }
    });
});
2
@ Satpal is this correct .... jQuery.validator.addMethod("showNic", function(value, element) { return this.optional(element) || /^[0-9]{9}[vVxX]$/.test(value); }, "Please enter correct NIC ");Erandi

2 Answers

2
votes

you have to add method

$.validator.addMethod('NICNumber', function (value) { 
    return  /^[0-9]{9}[vVxX]$/.test(value); 
}, 'Please enter a valid National Identity Card Number.');

Then you would add to your rules:

showNic: {
      required: true,
      NICNumber: true
},
0
votes

JavaScript Solution

var cnic_no = '922781800x',
cnic_no_regex = /^[0-9+]{9}[vVxX]{1}$/;

if(cnic_no_regex.test(cnic_no)) 
{
    alert('Right');
}
else 
{
    alert('Wrong');
}