gpt4 book ai didi

javascript - setCustomValidity 的问题

转载 作者:行者123 更新时间:2023-11-28 18:32:13 28 4
gpt4 key购买 nike

我正在编写一个简单的 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");
}
}

最佳答案

您所做的错误是customValidity仍然是“它们不匹配”,因为您没有将其设置为空字符串(浏览器将其视为成功验证),因此输入仍为一次验证失败后的相同状态。

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("");
}

}

关于javascript - setCustomValidity 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37769279/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com