如何在React Js中设置匹配密码

时间:2018-07-02 21:13:21

标签: javascript reactjs react-redux reactive-programming

我需要一些帮助,如何在React js中匹配密码。我使用了ant设计,第一个密码有效,但对于一致密码,我就声明它不起作用

handlePasswordChange = event => {
  this.setState({
    password: event.target.value,
  });
};
handleConfirmPassword = event => {
  if (event.handleConfirmPassword !== event.handlePasswordChange) {
    message.error('error');
  }
};

这些很有趣,下面是蚂蚁设计

<FormItem {...styles.formItemLayout} label="Password">
  {getFieldDecorator('Password', {
    rules: [{ required: true, message: 'Password is Required!' }],
  })(
    <Input
      onChange={this.handlePasswordChange}
      name="password"
      type="password"
      value={password}
      style={styles.margin}
    />,
  )}
</FormItem>
<FormItem {...styles.formItemLayout} label="Confirm Password">
  {getFieldDecorator('Confirm Password', {
    rules: [{ required: true, message: 'Confirm your Password!' }],
  })(
    <Input
      name="password"
      type="password"
      style={styles.margin}
      onChange={this.handleConfirmPassword}
    />,
  )}
</FormItem>

5 个答案:

答案 0 :(得分:7)

假设您的密码和ConfirmPassword都处于状态。

this.state = {
    password: '',
    confirmPassword: ''
}

handleSubmit = () => {
    const { password, confirmPassword } = this.state;
    // perform all neccassary validations
    if (password !== confirmPassword) {
        alert("Passwords don't match");
    } else {
        // make API call
    }
}

答案 1 :(得分:4)

尝试一下:

handleConfirmPassword = (event) => {
    if (event.target.value !== this.state.password) {
      message.error('error');
    }
}

您还可以将状态设置为:

state = {
    password: '',
    confirmPassword: ''
}

然后,您可以在handleConfirmPassword和提交上检查匹配项。

handleConfirmPassword = (event) => {
    if (event.target.value !== this.state.password) {
      message.error('error');
      this.setState({confirmPassword: event.target.value})
    }
}

然后,向表单提交处理程序:

handleSubmit = (event) => {
   if(this.state.password !== this.state.confirmPassword){
       message.error("The passwords doesn't match")
       return false; // The form won't submit
   }
   else return true; // The form will submit
}

答案 2 :(得分:1)

import { useForm } from 'react-hook-form'

const { register, errors, handleSubmit, formState } = useForm({
    mode: "onChange"
  })

  const [newpassword, setNewPassword] = useState('')

  const [confirmpassword, setConfirmPassword] = useState('')

  const  { touched  } = formState;

  const onVerifyNewPassword = () => {

    if(touched.newpassword === true && touched.confirmpassword === true){
      if(newpassword !== confirmpassword){
        console.log('The passwords dont match')
        return
      }else{
        console.log('Ok.')
      }
   }
  }

              <form onSubmit={handleSubmit(onSubmit)}>
                <div className="input-group">
                  <label htmlFor="new">New Password</label>
                </div>
                <input type="newpassword"
                  ref={register({ required: true })}

                  name="newpassword"
                  onChange={(e) => setNewPassword(e.target.value)}
                  onBlur={onVerifyNewPassword}
                />
                <label htmlFor="new">Confirm Password</label>
                <input type="confirmpassword"
                  ref={register({ required: true })}
                  name="confirmpassword"
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  onBlur={onVerifyNewPassword}



               />
                {/* <pre>{JSON.stringify(formState, null, 2)}</pre> */}


                <button><span>Change</span></button>

答案 3 :(得分:0)

您可以使用密码检查回调:

checkPassword = (rule, value, callback) => {
  if (value && value !== form.getFieldValue('Password')) {
    callback("The passwords don't match");
  } else {
    callback();
  }
};

通过validator规则:

<FormItem {...styles.formItemLayout} label="Password">
  {getFieldDecorator('Password', {
    rules: [{ required: true, message: 'Password is Required!' }],
  })(
    <Input
      name="password"
      type="password"
      value={password}
      style={styles.margin}
    />,
  )}
</FormItem>
<FormItem {...styles.formItemLayout} label="Confirm Password">
  {getFieldDecorator('ConfirmPassword', {
    rules: [
      { required: true, message: 'Confirm your Password!' }, 
      { validator: this.checkPassword }
    ],
  })(
    <Input
      name="password"
      type="password"
      style={styles.margin}
    />,
  )}
</FormItem>

答案 4 :(得分:0)

我只是以为我也要投入两分钱:)

import React, {Component} from 'react';

class Form extends Component {

  constructor(props) {
    super(props)
    this.state = {
      password: {
        new: null,
        match: null,
        confirmed: null,
      },
    }
    this._handleNewPassword = this._handleNewPassword.bind(this)
    this._handlePasswordMatch = this._handlePasswordMatch.bind(this)
    this._handleFormSubmission = this._handleFormSubmission.bind(this)
    this._handleConfirmedPassword = this._handleConfirmedPassword.bind(this)
  }


  _handleFormSubmission({ currentTarget }) {
    // Check the password 
    // match on form submission
    this._checkPasswordForMatch().then(
      ({ success }) => {
        if (success) {
          // post data to API
        } 
      }
    )
  }

  // handle storing the
  // new password in state
  _handleNewPassword(value) {
    let state = Object.assign({}, this.state)
    state.password.new = value 
    this.setState(state)
  }

  // handle storing the
  // confirmed password in state   
  _handleConfirmedPassword(value) {
    if (value === this.state.password.new) {
      let state = Object.assign({}, this.state)
      state.password.confirmed = value;
      this.setState(state);
    }
  }

  // handle storing the
  // confirmed password in state  
  async _handlePasswordMatch() {
    let { password } = this.state;
    let state = Object.assign({}, this.state);
    if (password.new === password.confirmed) {
      state.password.match = true        
    } else {
      state.password.match = false
    }
    await this.setState(state)
    return {
      success: state.password.match
    }   
  }

  render() {
    return (
       <div 
        method='POST'
        onFormSubmit={this._handleFormSubmission}>
        <input 
          type='password'
          name='new-password'
          onChange={this._handleNewPassword}
          pattern='(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}' />
        <input 
          type='password'
          name='confirm-password'
          onChange={this._handleConfirmedPassword}
          pattern='(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}' />
          <button type='submit'>Submit</button> 
      </div>
    );
  }
}

export default Form;