如何检测尝试提交的无效HTML表单



使用HTML表单验证时,表单中的输入值无效将停止提交该表单。如何检测用户尝试表单提交失败?当提交因验证失败而停止时,表单的onsubmit处理程序不会激发。

我目前正在监听提交按钮上的keypressclick事件,以检测提交尝试。有没有更好的方法来检测失败的表单提交?

绕过这一问题的一个简单方法是向表单中的每个输入添加一个事件侦听器,以查看它何时被阻止提交。"无效"事件应该完成您需要的所有操作。

示例

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/

我建议您使用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
}

您可以在此处查看:https://jsfiddle.net/titulus_desiderio/Laon29f3/

基于上面的@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;

最新更新