Function to validate CNIC using Regex

Solution

In JQuery

    var checkCNIC = function (textBox) {

                debugger;

                 var regexp = new RegExp('^[0-9+]{5}-[0-9+]{7}-[0-9]{1}$');
                 var check = textBox.value;
                if (!regexp.test(check)) {

                    alert('Invalid CNIC');
                    $(textBox).css('border-color', 'red');
                    return false;

                }
                else {
                    $(textBox).css('border-color', 'green');
                    $(textBox).value = check;
                    return true;
                }
}

In HTML

    @Html.TextBox("AddCNIC", null, new { @class = "form-control text-box", @placeholder = "11111-1111111-1", @onchange = "checkCNIC(this)" })

Explanation

This regex will allow you to enter the CNIC in this format 12345-1234567-1

i.e. 5 numbers then a dash followed by 7 numbers and a dash and at last a number

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Blog at WordPress.com.

Up ↑

Create your website at WordPress.com
Get started
%d bloggers like this: