jqueryregexjquery-validate

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.


Solution

  • 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}$/