使用HTML5 表单验证时,表单中的输入值无效将停止提交该表单。如何检测用户尝试提交失败的表单?当提交因验证失败而停止时,表单的onsubmit
处理程序不会触发。
我目前正在监听提交按钮上keypress
的click
事件以检测提交尝试。有没有更好的方法来检测表单提交失败?
使用HTML5 表单验证时,表单中的输入值无效将停止提交该表单。如何检测用户尝试提交失败的表单?当提交因验证失败而停止时,表单的onsubmit
处理程序不会触发。
我目前正在监听提交按钮上keypress
的click
事件以检测提交尝试。有没有更好的方法来检测表单提交失败?
解决此问题的一种简单方法是为表单中的每个输入添加一个事件侦听器,以查看何时阻止提交。'invalid' 事件应该做你需要的一切。
例子
Array.prototype.slice.call(document.querySelectorAll("[required]")).forEach(function(input){
input.addEventListener('invalid',function(e){
//Your input is invalid!
})
});
更多信息在这里 http://www.html5rocks.com/en/tutorials/forms/constraintvalidation/
在上面的@Titulus代码的基础上,这是我在 jQuery 中的做法;如果需要,您可以将其调整为本地事件。
$('form-selector').on('submit', function(event) {
// Don't do anything if constraint validation isn't supported by the browser.
if (
!('checkValidity' in this) ||
// In the unlikely case this is a property but not actually a function.
// Hypothetically, a botched polyfill could do this; it pays to be careful
// and build resilient code.
typeof this.checkValidity !== 'function'
) {
return;
}
if (this.checkValidity() === true) {
// Valid values code.
} else {
// Invalid values code.
// Leave this until the last possible moment in the handler in case there's
// an error in any of the handler code to reduce the chances of a broken
// form where the submit does nothing. If an exception is thrown before
// this, the browser shouldn't get this far, (hopefully) allowing the basic
// form to still work.
event.preventDefault();
}
});
// Tell the browser to not validate automatically, as that would prevent submit
// from being triggered. We prevent the submission above if form doesn't pass
// validation. This is here in case there's an error in the preceding code, so
// this (hopefully) doesn't get applied in that case and browser validation
// takes place as a fallback.
this.noValidate = true;
我建议你使用noValidate
属性。您可以关闭默认验证,并在onsubmit
方法中手动运行它
var form = document.getElementById("myForm");
form.noValidate = true; // turn off default validation
form.onsubmit = function(e) {
e.preventDefault(); // preventing default behaviour
this.reportValidity(); // run native validation manually
// runs default behaviour (submitting) in case of validation success
if (this.checkValidity()) return form.submit();
alert('invalid'); // your code goes here
}