I am using the following regex in .NET to validate that a string contains 12 numeric characters and it works perfectly. (EG: 000000174064)
public static string TwelveDigitNumber = @"^\d{12}$";
However that same regular expression does not work client side using javascript.
EDIT: I am using jquery validate, and have added the following function for regular expresssions
// regex validation
$.validator.addMethod(
"regex",
function (value, element, regexp) {
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
},
"Please check your input."
);
rules: {
"Number": {
maxlength: 12, regex: "^\d{12}$"
},
The result from
new RegExp( "^\d{12}$" )is/^d{12}$/instead of/^\d{12}$/because of the escape backslash. It works in .NET because you have @ which I think skips the escaping.Anyway, for static regexes you can just use regex literals:
regex: /^\d{12}$/is same as
regex: new RegExp( "^\\d{12}$" )You can then pass it directly to the function and it doesn’t have to instantiate it every time.