将动态表单验证回调添加到字段

时间:2017-01-11 15:06:16

标签: javascript jquery validation

我正在使用formValidation.io,需要在类中动态添加callback类型验证器,以便它可以使用类属性。问题是我最初将验证器选项传递给super调用,该调用具有一些表单验证过程。但这意味着我没有对类属性的初始访问权。

所以为了做到这一点,我试图使用updateOption,但它肯定没有开始验证这一点。

class MyForm extends Form {

  var validatorOptions = {
    fields: {
      phoneNumber: {
        validators: {
          regexp: {
            regexp: Regexp.phone,
            message: "Please enter a valid phone number"
          }
        }
      }
    }
  };

  super({
    validator: {
      options: validatorOptions
    }
  });
  var self = this;

  this._cachedPhoneNumbers = [];

  var phoneValidatorCallback = {
    message: "This number is already in use",
    callback: function(value, validator, $field) {
      if ($.inArray(value, self._cachedPhoneNumbers) > -1)
        return false;
      return true;
    }
  }

  // ref to validator is definitely valid!
  this.validator.updateOption('phone', 'callback', 'callback', phoneValidatorCallback);

}

1 个答案:

答案 0 :(得分:0)

这是答案。我只是误用了这个功能。

class MyForm extends Form {

  var validatorOptions = {
    fields: {
      phoneNumber: {
        validators: {
          regexp: {
            regexp: Regexp.phone,
            message: "Please enter a valid phone number"
          },
          callback: {
            message: 'This number is in use',
            callback: function() {
              return true;
            }
          }
        }
      }
    }
  };

  super({
    validator: {
      options: validatorOptions
    }
  });
  var self = this;

  this._cachedPhoneNumbers = [];

  function phoneValidatorCallback(value, validator, $field) {
    if ($.inArray(value, self._cachedPhoneNumbers) > -1)
      return false;
    return true;
  }

  // ref to validator is definitely valid!
  this.validator.updateOption('phone', 'callback', 'callback', phoneValidatorCallback);

}