我使用react.js/bootstrap制作了一个登录/注册表单,在注册表单中我有4个输入。 1 个用于用户名,1 个用于电子邮件,2 个用于密码(1 个密码和 1 个用于确认目的),如果 2 个密码不匹配,我想显示一条消息,例如密码不匹配。
在检查 2 个密码输入后,我尝试添加无效反馈 boostrap 类,但它没有按预期工作这是我正在使用的代码:
function handleSubmit(e) {
e.preventDefault();
const form = e.target;
passwordChecker();
if (form.checkValidity()) {
handleLoginClick();
reset();
console.log("Form submitted successfully");
} else {
form.classList.add('was-validated');
}
}
function passwordChecker(){
const confirmPasswordField = document.querySelector("#invalidpassword1");
if (isRegistering && password !== checkPassword) {
form.classList.add('was-validated');
confirmPasswordField.classList.add("invalid-feedback");
console.log("passwords dont match")
} else {
confirmPasswordField.classList.remove("invalid-feedback");
console.log("passwords match")
}
}
<div className="form-floating mb-3">
<input
type="password"
className="form-control"
id="registerPassword"
placeholder="Enter your password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
<label htmlFor="registerPassword">Password</label>
<div className='invalid-feedback' id='invalidpassword2'>Please fill out this field</div>
<div className="form-floating mb-3">
<input
type="password"
className="form-control"
id="confirmPassword"
placeholder="Confirm your password"
value={checkPassword}
onChange={(e) => setCheckPassword(e.target.value)}
required
/>
<label htmlFor="confirmPassword">Confirm Password</label>
<div id='invalidpassword1'>Passwords do not match</div>
</div>
我尝试过的新代码
<div id='invalidpassword1' className='invalid-feedback'>{checkPassword==='' ? 'Please fill out this field' : 'Passwords do not much'}</div>
现在会弹出正确的消息,但方程式仍然不起作用,当密码不匹配时,它会显示正确
根据引导文档,无效/有效的自定义反馈消息必须包含在具有
<form>
属性的 novalidate
中。
https://getbootstrap.com/docs/5.0/forms/validation/#custom-styles
setCustomValidity()
因此,获取输入字段并将其有效性设置为某些内容(例如,避免显示消息的空格):
if (isRegistering && password !== checkPassword) {
form.classList.add('was-validated');
confirmPasswordField.classList.add("invalid-feedback");
console.log("passwords dont match")
const input = document.querySelector('#confirmPassword');
input.setCustomValidity(" ");
input.reportValidity();