10

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

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>
3
  • 7
    Welcome to Stack Overflow! Please do not vandalise your posts. Once you have submitted a post, you have licensed the content to the Stack Overflow community at large (under the CC BY-SA license). By SE policy, any vandalism will be reverted. Commented Jul 3, 2018 at 13:09
  • 1
    How we can do this on each character match not on form submission? Please suggest. Commented Sep 11, 2019 at 5:08
  • 1
    You can do it easily using react-hook-form.com. check it here. codesandbox.io/s/react-password-match-oq97w Commented Apr 26, 2020 at 3:56

7 Answers 7

17

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
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Hey, Is this possible to check confirm password each character value but not on form submission? I want to show an error if a single character on the change of password doesn't match. Please help if you have any solution
9

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 handleConfirmPassword and on the submit.

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
}

Comments

1

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 validator rule:

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

Comments

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>

1 Comment

Welcome to StackOverflow! Please provide explanation in addition to the code so that users can easily understand how your answer fixes the problem posed in the question.
0

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;

Comments

0

This is state that contains data :

    this.state = {
        name: '',
        email: '',
        password: '',
        confirmpass: '',
      
    }
}

Update password and confirm password :

onpasschange= (e) => {
    this.setState({ password: e.target.value })
}
oncpasschange = (e) => {
    this.setState({ confirmpass: e.target.value })
}

HTML Form :

  <div className="form-group">
          <label className="lable" htmlFor="exampleInputPassword1">
            Password
          </label>
          <input
            type="password"
            value={this.state.password}
            onChange={this.onpasschange}
            className="form-control"
            id="exampleInputPassword1"
            placeholder="Password"
          />
        </div>
        <div className="form-group">
          <label htmlFor="exampleInputPassword1">Confirm Password</label>
          <input
            type="password"
            value={this.state.confirmpass}
            onChange={this.oncpasschange}
            className="form-control"
            id="exampleInputPassword1"
            placeholder="Password"
          />
        </div>

handle events:

  click= (e)={      

 if (this.state.password !== this.state.confirmpass) {
  alert("Passwords don't match");   // alert when password doesn't match
} else {   
  alert('correct');   // alert when password  match
}

};

Comments

0

what I did was this;

`const [password, setPassword] = useState("");
  const [matchpassword, setMatchPassword] = 
    useState("");
  const [error, setError] = useState("");

const onSubmitHandler = (e) => {
e.preventDefault();

if(!matchPassword.match(password){
alert("Passwords do not match!")
} else if(matchPassword.length !== password.length) 
 {
alert("Passwords do not match!")
} else{
alert("continue")
}
}


function handleSetMatchPassword(event) {
setMatchPassword(event.target.value);
let match_pass = event.target.value;
setMatchPassword(match_pass);

if (!match_pass.match(password)) {
  setError("Passwords does not match!");
} else if (match_pass.length !== password.length) {
  setError("Passwords does not match!");
} else {
  setError("Passwords match!");
 }
}


return(
  <div>
    <div>
      <input
            type="password"
            onChange={handlePasswordChange}
            value={password}
            name="password"
            id="passWord"
            placeholder="Password"
            required
          />
   </div>
   <div>
    <input
            type="password"
            value={matchPassword}
            onChange={handleSetMatchPassword}
            name="matchPassword"
            id="coPassword"
            placeholder="Confirm password"
            required
          />
     </div>
       <div>
         {error}
     </div>
  </div>
       )`

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.