I have this jquery validate add method below with a specific regex.
What I want is to create a method that returns the regex, like in my second example, but the second example doesn't work. I get some error that says 'Object doesn't support property or method 'test'
if (scope.countryCode == "DE") {
$.validator.addMethod('PostalCodeError',
function(value) {
return /^(?!01000|99999)(0[1-9]\d{3}|[1-9]\d{4})$/.test(value);
}, 'Please enter a valid German postal code.');
$("#PostalCode").rules("add", {
PostalCodeError: true
});
}
I want something like this below
$.validator.addMethod('PostalCodeError',
function(value) {
return GetCountryRegex().test(value);
}, 'Please enter a valid postal code.');
$("#PostalCode").rules("add", {
PostalCodeError: true
});
function GetCountryRegex() {
if (scope.countryCode == "DE") {
return '/^(?!01000|99999)(0[1-9]\d{3}|[1-9]\d{4})$/';
}
if (scope.countryCode == "AT") {
return '/^\\d{4}$/';
}
}
/regexp/and'/regexp/'are 2 different things (the second is a string). Try withreturn new RegExp('regexp');