Question

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.

Was it helpful?

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

OTHER TIPS

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})

(([[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01]))-([0-9]{2})-([0-9]{4})

This is the most strict IC regex that I can found.

This regex will make sure the IC is born incorrect Day, Month, Year.

This solution is really good. But, I want to add what it cannot do:

  1. Identify how many days in that month.

For example: it will return true if the month is 11 (November) and day 31, which we knew that there is no way November has 31th day.

  1. Identify leap year for February, since its day will be either 28 or 29 when in leap year.

Test this regex on https://www.regextester.com/, copy the answer and paste it in regular expression input.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top