[英]Adding onto browsers' built-in form validation
I'm creating an email form for our website. 我正在为我们的网站创建一个电子邮件表单。 I built the form using HTML5 and CSS to take advantage of browsers' built-in validation (using this shim to avoid compatibility problems).
我使用HTML5和CSS构建了表单,以利用浏览器的内置验证功能 (使用此填充程序可避免兼容性问题)。 Now I want to add a "confirm your email address" field, which shouldn't be marked valid unless it matches the "enter your email address" field.
现在,我要添加“确认您的电子邮件地址”字段,除非该字段与“输入您的电子邮件地址”字段匹配,否则不应将其标记为有效。
I've written some JavaScript to compare the two fields. 我已经编写了一些JavaScript来比较这两个字段。 Is there a way for JavaScript to mark a field as valid/invalid for the browser's built-in validation?
JavaScript有没有办法将字段标记为对浏览器的内置验证有效/无效? Or do I need to switch to a third-party validation plugin to get this feature?
还是我需要切换到第三方验证插件才能获得此功能?
Found the answer right after I posted the question. 我发布问题后立即找到答案 。 You call
<element>.setCustomValidity()
on the field, passing in an empty string to set the field as valid. 您在字段上调用
<element>.setCustomValidity()
,传入一个空字符串以将该字段设置为有效。 If it's not valid, you instead pass in a string with the reason why. 如果无效,则改为输入原因。
Here's my code: 这是我的代码:
$('#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.");
}
});
Here it is again without jQuery: 这又是没有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.");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.