Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Malaysian Identity Card (IC) Regular Expression - jQuery

I have what I thought was a correct regular expression for checking a Malaysian IC card:

\d{6}-\d{2}-\d{4} (ie. Numbers in the format xxxxxx-xx-xxxx where x is a digit from 0-9)

However, when I insert it into my jQuery to validate it is never allowing it to submit the form despite it being written in the correct format.

Here is my code:

<script type="text/javascript"> 

$.validator.setDefaults({
    submitHandler: function(form) {
        form.submit();
    }
});

$.validator.addMethod("regex", function (value, element, regexp) 
{
    var check = false;
    var re = new RegExp(regexp);
    return this.optional(element) || re.test(value);
}, "Please enter a valid ic number");

$(document).ready(function () {

    // validate signup form on keyup and submit
    $("#commentForm").validate({
        rules: {
            ic_no: {
                required: true,
                regex: "\d{6}\-\d{2}\-\d{4}"
            }
        },
        messages: {
            ic_no: {
                required: "Please input the IC number before searching.",
                regex: "Please enter a valid ic number."
            }
        }
    });

}); 

I'm not an expert in either javascript or regular expressions but I thought this "should" work. Any pointers would be greatly appreciated.

like image 793
nematoth Avatar asked Apr 25 '14 07:04

nematoth


2 Answers

You have to escape the backslashes inside strings that will be passed to the RegExp constructor:

regex: "\\d{6}\\-\\d{2}\\-\\d{4}"

I would also recommend adding anchors to it:

regex: "^\\d{6}\\-\\d{2}\\-\\d{4}$"

This way you will consider "1234567-12-12345" as invalid.

Update

Alternatively, you can pass a RegExp object using a literal expression:

regex: /^\d{6}-\d{2}-\d{4}$/
like image 64
Ja͢ck Avatar answered Sep 29 '22 21:09

Ja͢ck


Instead of checking the length of the number, we could check the number they could insert by using the following regex. Isn't it better?

(([0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01]))-([0-9]{2})-([0-9]{4})
like image 44
Yew Hong Tat Avatar answered Sep 29 '22 22:09

Yew Hong Tat