如何在onChange的表单验证中比较两个输入值是否相同



我在用钩子在功能组件中输入数据时创建了一个表单验证,在确认密码并返回密码之前,一切都很好。当确认密码输入已经存档,并且我对密码输入进行了更改时,它没有看到更改,确认密码中的错误也不会出现。我不知道如何让验证检测输入中的更改,并在密码===确认密码时再次检查。

export default function Register() {
const [error, setError] = useState({
username: false,
email: false,
password: false,
confirmPassword: false,
consent: false
})
const handleChange = (e) => {
let emailver = /^S+@S+.S+$/;
let passValidation = /(?=.*[!#@$^%*])[a-zA-Z0-9!#@$%*^]{6,100}$/;
switch (e.target.name) {
case "username": (e.target.value.length <= 4 && e.target.value !== '')
? setError({ ...error, username: true })
: setError({ ...error, username: false })
break;
case "email": (emailver.test(e.target.value) || e.target.value === '')
? setError({ ...error, email: false })
: setError({ ...error, email: true })
break;
case "password": (!e.target.value.match(passValidation) && e.target.value !== '')
? setError({ ...error, password: true })
: setError({ ...error, password: false })
break;
case "confirm-password": (e.target.value !== document.getElementsByName('password')[0].value)
? setError({ ...error, confirmPassword: true })
: setError({ ...error, confirmPassword: false })
break;
default:
break;
}
}

return (
<div>
<div className="login">
<h2>Register</h2>
<div className="login-box">
<form noValidate >
<input type="text" name="username" placeholder="Username" className={(error.username) ? 'error' : ''} onChange={handleChange} />
{(error.username) ? <span className="register-info">(Username has to be atleast 5 charaters long.)</span> : ''}
<input type="email" name="email" placeholder="E-mail" className={(error.email) ? 'error' : ''} onChange={handleChange} />
{(error.email) ? <span className="register-info">(Invalid e-mail.)</span> : ''}
<input type="password" name="password" placeholder="Password" className={(error.password) ? 'error' : ''} onChange={handleChange} />
{(error.password) ? <span className="register-info">Password should be 6 letters long and include one special character (! # @ $ %).</span> : ''}
<input type="password" name="confirm-password" placeholder="Confirm password" className={(error.confirmPassword) ? 'error' : ''} onChange={handleChange} />
{(error.confirmPassword) ? <span className="register-info">Passwords does not match</span> : ''}
<div className="consent">
<input type="checkbox" id="approval" className="approval" />
<label htmlFor="approval">Consent.</label>
</div>
<input type="submit" value="Register" id="reg-bt" />
</form>
<p><Link to="/"  className="login-link">Login</Link></p>
</div>
</div>
</div>
)

}

您需要比较passwordconfirm-password

case "password":
!e.target.value.match(passValidation)?
setError({ ...error, password: true }):
e.target.value !== document.getElementsByName("confirm-password")[0].value ?
setError({ ...error, confirmPassword: true })
: setError({ ...error, password: false });
break;

相关内容

  • 没有找到相关文章

最新更新