javascript 如何在反应 Js 中设置匹配密码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51143800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:26:01  来源:igfitidea点击:

How to set match password in react Js

javascriptreactjsreact-reduxreactive-programming

提问by ALVIN

I need some help how could I match the password in react js. I used ant design the first password is working but for conform password I put statement its not working how could I do it

我需要一些帮助如何匹配 react js 中的密码。我使用 ant design 第一个密码有效,但对于符合密码,我声明它不起作用我该怎么做

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

these are fun and below is the ant design

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

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

回答by Erick

Assuming that both your password and confirmPassword are in state.

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

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

回答by reisdev

Try this:

试试这个:

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

You can also set your state like:

您还可以将状态设置为:

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

And then, you can check the match on the handleConfirmPasswordand on the submit.

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

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

And then, a submit handler to the form:

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

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
}

回答by froston

You can use password check callback:

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

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

Thru validatorrule:

通过验证器规则:

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

回答by White Rabbit

I just thought I'd throw my two cents in as well :)

我只是想我也会投入我的两分钱:)

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;