javascript - setCustomValidity 的问题

标签 javascript html

我正在编写一个简单的 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/

相关文章:

javascript - 导出为 CSV 时的编码问题

php - 在 HTML 页面中显示纯 PHP 代码

javascript - 检查字符串中是否有较小/较大的符号

javascript - 如何将附加参数传递给事件处理程序?

javascript - 制作一个有点 flex 的 div

javascript - 如何使用 jquery 从类中获取 css 属性

javascript - 如何将 DIV 上的填充底部转换为其包含的 DIV 上的负边距?

javascript - 非常小的 jsfiddle 的 DOM 泄漏与 jquery

javascript - HTML 选择元素 - 自定义默认值? (跨浏览器解决方案)

javascript - 100% 屏幕尺寸,无论分辨率如何