代码之家  ›  专栏  ›  技术社区  ›  chuckd

javascript返回字符串作为jquery的regex validate add方法

  •  1
  • chuckd  · 技术社区  · 7 年前

    我在下面用一个特定的regex来验证jquery-validate-add方法。

    我想创建一个返回regex的方法,就像在第二个示例中一样,但是第二个示例不起作用。我得到一个错误,说“对象不支持属性或方法”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
      });
    }
    

    我想要下面这样的东西

    $.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}$/';
      }
    }
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   Matthew Herbst    7 年前

    所以,在 GetCountryRegex 你实际上没有返回regex,你返回的字符串。

    使用 new RegExp 在将字符串转换为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(...);