6

我在这里尝试做一个“字段 2 与字段 1 不匹配”的事情(即“密码不匹配”)。

没有太多关于 antd 表单可用规则的​​文档。他们在这里指着这个项目。

以下是我目前的表格:

const ResetPasswordForm = Form.create()(React.createClass({
  getInitialState () {
    return {
      loading: false
    };
  },
  handleSubmit(e) {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (err) {
        failure();
      }
      if (!err) {
        let newPassword = values.newPassword;
        let repeatNewPassword = values.repeatNewPassword;
        handleResetPassword(newPassword, repeatNewPassword, this.props.token);
      }
    });

  },
  render() {
    const { getFieldDecorator } = this.props.form;

    const newPasswordRules = [
      { required: true, message: 'Please input a new password!' }
    ];

    const repeatNewPassword = [
      { required: true, message: 'Please repeat the new password!' }
    ];

    return (
      <Form onSubmit={this.handleSubmit} className="login-form">
        <FormItem>
          {getFieldDecorator('newPassword', { rules: newPasswordRules })(
            <Input addonBefore={<Icon type="lock" />} type="password" placeholder="New password" />
          )}
        </FormItem>
        <FormItem>
          {getFieldDecorator('repeatNewPassword', { rules: repeatNewPassword })(
            <Input addonBefore={<Icon type="lock" />} type="password" placeholder="Repeat new password" />
          )}
        </FormItem>
        <FormItem>
          <Button loading={this.state.loading} type="primary" htmlType="submit" className={css(styles.loginButton)}>
            Reset Password
          </Button>
        </FormItem>
      </Form>
    );
  }
}));

如果有人能指出我正确的方向来创建一个检查第一个字段值是否与第二个匹配的规则,那就太棒了!

4

2 回答 2

10

您可以在此注册表单演示中找到它:https ://ant.design/components/form/#components-form-demo-register

于 2017-01-07T15:02:30.217 回答
4

请遵循以下几行:

  <Form.Item
    name="password"
    label="Password"
    rules={[
      {
        required: true,
        message: 'Please input your password!',
      },
    ]}
    hasFeedback
  >
    <Input.Password />
  </Form.Item>

  <Form.Item
    name="confirm"
    label="Confirm Password"
    dependencies={['password']}
    hasFeedback
    rules={[
      {
        required: true,
        message: 'Please confirm your password!',
      },
      ({ getFieldValue }) => ({
        validator(rule, value) {
          if (!value || getFieldValue('password') === value) {
            return Promise.resolve();
          }
          return Promise.reject('The two passwords that you entered do not match!');
        },
      }),
    ]}
  >
    <Input.Password />
  </Form.Item>
于 2020-07-07T13:40:12.210 回答