How to set match password in react Js
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
}
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>
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
}
}
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>