我正在为我们的网站创建电子邮件表单。我建立了表格 using HTML5 and CSS利用 browsers' built-in validation (使用 this shim 以避免兼容性问题)。现在我想添加一个“确认您的电子邮件地址”字段,除非它与“输入您的电子邮件地址”字段匹配,否则不应将其标记为有效。
我编写了一些 JavaScript 来比较这两个字段。 JavaScript 有没有办法将字段标记为浏览器内置验证的有效/无效?或者我是否需要切换到第三方验证插件才能获得此功能?
最佳答案
找到the answer就在我发布问题之后。您调用<element>.setCustomValidity()
在字段上,传入一个空字符串以将该字段设置为有效。如果无效,您可以传入一个字符串并说明原因。
这是我的代码:
$('#emailConfirmation').on('keyup', function() {
if ($('#emailConfirmation').val() == $('#email').val()) {
$("#emailConfirmation")[0].setCustomValidity("");
} else {
$("#emailConfirmation")[0].setCustomValidity("Check that you've typed your email address the same way in both places.");
}
});
这里又是没有 jQuery 的情况:
document.getElementById('emailConfirmation').onchange = function() {
if (document.getElementById("emailConfirmation").value == document.getElementById("email").value) {
document.getElementById("emailConfirmation").setCustomValidity("");
} else {
document.getElementById("emailConfirmation").setCustomValidity("Check that you've typed your email address the same way in both places.");
}
}
关于javascript - 添加到浏览器的内置表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33265066/