getFieldDecorator rules for password reset?

11.8k views Asked by At

I'm trying to do a "field 2 does not match field 1" thing here (i.e. "passwords do not match).

There isn't much documentation on the available rules for the antd forms. They point at this project here.

Below is my current form:

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>
    );
  }
}));

If anyone can point me in the right direction for creating a rule that checks that the first field value matches the second, that'd be awesome!

2

There are 2 answers

0
afc163 On BEST ANSWER

You can find it in this register form demo: https://ant.design/components/form/#components-form-demo-register

0
Alex K - JESUS first On

Please, follow these lines:

  <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>