Reputation: 14540
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}$/';
}
}
Upvotes: 1
Views: 157
Reputation: 31983
So, in GetCountryRegex
you're not actually returning RegEx, your returning strings.
Use new RegExp
on the returned value to convert the strings to RegExp:
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}$/';
}
}
var regExp = new RegExp(GetCountryRegex());
regExp.test(...);
Upvotes: 3