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.
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.
Alternatively, you can pass a RegExp object using a literal expression:
regex: /^\d{6}-\d{2}-\d{4}$/
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})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With