我正在编写一个简单的if语句来测试每个输入框中的密码是否匹配。如果它们都匹配,则不会给出错误,如果它们不匹配,则使用.setCustomValidity()给出“它们不匹配”的错误。我遇到的问题是当给出错误然后更正密码以匹配时,仍然会给出错误。我不确定我做错了什么。下面是我的代码和一个工作JSfiddle的链接。
JSfiddle:https://jsfiddle.net/1934foej/
HTML:
<label>
<input id="first" type="text" min="16" max="100" placeholder="New password" autofocus required>
</label>
<label>
<input id="second" type="text" min="16" max="100" placeholder="Repeat password" required>
</label>
<input id="submit" type="submit">
JS:
var firstPasswordInput = document.querySelector('#first');
var secondPasswordInput = document.querySelector('#second');
var submit = document.querySelector('#submit');
submit.onclick = function () {
var firstPassword = firstPasswordInput;
var secondPassword = secondPasswordInput;
//checks for match
if( firstPassword.value !== secondPassword.value) {
firstPasswordInput.setCustomValidity("they do not match");
}
}
答案 0 :(得分:3)
您正在执行的错误是customValidity仍为"they do not match"
,因为您没有将其设置为空字符串(浏览器将其视为成功验证),因此在一次验证失败后输入仍保持相同状态。
submit.onclick = function() {
// there is no need to redefine these two variables
var firstPassword = firstPasswordInput;
var secondPassword = secondPasswordInput;
if(firstPassword.value !== secondPassword.value) {
firstPassword.setCustomValidity("they do not match");
}
//add this part
else {
firstPassword.setCustomValidity("");
}
}