[英]Javascript form validation: custom error message
https://codepen.io/durja/pen/BPmmyR
我正在尝试使用html中的约束API为表单实现自定义错误消息。 下面是我的代码,我面临一个问题,在输入错误的输入并再次对其进行更正后,验证消息仍会显示。 我不确定我缺少什么。 我什至尝试使用checkValidity()方法检查有效性,即使输入的格式正确,该方法也会返回false。
const fp = document.getElementById('quantity');
const ide = document.getElementById('ide_pref');
fp.addEventListener('input',e => {
console.log(e.target.value);
if(fp.validity.rangeOverflow) {
fp.setCustomValidity('Custom message: greater than 100 not allowed.');
}
});
ide.addEventListener('input',e => {
console.log(e.target.value);
console.log(ide.checkValidity());
if(ide.validity.patternMismatch) {
ide.setCustomValidity('enter exactly webstorm OR vscode');
}
})
参见HTMLSelectElement.setCustomValidity()
HTMLSelectElement.setCustomValidity()方法将选择元素的自定义有效性消息设置为指定的消息。 使用空字符串表示元素没有自定义有效性错误。
您目前永远不会重置自定义有效性消息,因此它仍然是'Custom message: greater than 100 not allowed.'
(或其他元素的其他消息)永远只要输入无效即可。 插入else
语句(如果没有rangeOverflow
或patternMismatch
),并使用空字符串调用setCustomValidity
以清除错误消息,以防单击按钮时存在错误消息:
const fp = document.getElementById('quantity'); const ide = document.getElementById('ide_pref'); fp.addEventListener('input', e => { if (fp.validity.rangeOverflow) { fp.setCustomValidity('Custom message: greater than 100 not allowed.'); } else { fp.setCustomValidity(''); } }); ide.addEventListener('input', e => { if (ide.validity.patternMismatch) { ide.setCustomValidity('enter exactly webstorm OR vscode'); } else { ide.setCustomValidity(''); } })
.u { margin-bottom: 15px; } .u:invalid { border: 2px solid orangered; } .u:valid { border: 2px solid greenyellow; } .btn { border: none; padding: 10px; border-radius: 8px; margin-top: 10px; } :focus { outline-color: gray; }
<form action="#" method="get"> <div> <label for="ide_pref">Would you prefer webstorm or vscode?</label> <input required class="u" type="text" pattern="webstorm|vscode" id="ide_pref" name="ide_pref"><br> <label for="quantity">How many licences would you like?</label> <input required class="u" type="number" min="1" max="100" id="quantity" name="lic_quantity"><br> <button class="btn" type="submit">Submit</button> </div> </form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.