如何使用自定义验证功能在Ant设计表单上触发字段验证

时间:2019-07-25 08:23:24

标签: antd

我有密码重设表格:

  {formItem(
          props.form.getFieldDecorator('currentPassword', {
        rules: [{ min: 6 },
          { validator: maybeMustBeRequared }
        ],
          })(<Input type="password" />),
          {
            label: tUsers.currentPassword,
          },
        )}
        {formItem(
          props.form.getFieldDecorator('newPassword', {
            rules: [{ min: 6 }],
          })(<Input type="password" />),
          {
            label: tUsers.newPassword,
          },
        )}
        {formItem(
          props.form.getFieldDecorator('confirmPassword', {
            rules: [
              { min: 6 },
              {
                validator: compareToFirstPassword,
              },
            ],
          })(<Input type="password" />),
          {
            label: tUsers.confirmPassword,
          },
        )}

passwordnewPassword不为空时,我的目标重新验证密码confirmPassword字段。

const maybeMustBeRequared = (rule, value, callback) => {
    console.log('rule', rule)
    if (!isEmpty(props.form.getFieldValue('newPassword')) || !isEmpty(props.form.getFieldValue('confirmPassword'))  ) {
      // there I want trigger passwor field validation { min: 6}
    } else {
      callback()
    }
  }

1 个答案:

答案 0 :(得分:0)

尽管我认为您不需要这种验证器,但两个规则min: 6都足够。

但是您仍然可以尝试以下方法:

  passwordLength = (rule, value, callback) => {
    const { form } = this.props;
    const confirmPassword = form.getFieldValue('confirmPassword');
    if (value || confirmPassword) {
      rule.validate('confirmPassword');
    } else {
      callback('Im Here');
    }
  };

Edit Q-57197421-CustomValidator