使用HTML5 form validation时,表单中的输入值无效将停止提交该表单。如何检测用户尝试表单提交失败?当验证失败提交暂停时,表单的onsubmit
处理程序不会触发。
我目前正在提交按钮上的keypress
和click
个事件来检测提交尝试。有没有更好的方法来检测失败的表单提交?
答案 0 :(得分:2)
解决此问题的一种简单方法是向表单中的每个输入添加一个事件侦听器,以查看何时阻止提交。 “无效”'事件应该做你需要的一切。
示例强>
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/
答案 1 :(得分:1)
在某个地方试试这个
var myForm = document.forms[0];var myFormElements = myForm.elements;
for(var i in myFormElements){
var element = myFormElements[i];
if(!element.willValidate){
continue;
}
element.addEventListener('invalid',function(e){
//Your input is invalid!
myForm.classList.add('validated');
});
}
答案 2 :(得分:0)
我建议您使用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
}
答案 3 :(得分:0)
以上面的@ 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;