1

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}$/';
  }
}
2
  • 2
    note that /regexp/ and '/regexp/' are 2 different things (the second is a string). Try with return new RegExp('regexp'); Commented Dec 19, 2018 at 8:20
  • I removed the Code Snippets. They are completely pointless if you don't include the proper HTML/CSS/JavaScript/plugins to make a live demo. Commented Dec 19, 2018 at 17:56

1 Answer 1

3

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(...);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.