简体   繁体   English

阻止表单提交但保留表单验证

[英]Prevent form submit but retain form validation

How do I retain the default HTML form validation and yet prohibit form submitting?如何在保留默认 HTML 表单验证的同时禁止表单提交? I have tried using event.preventDefault() and return false .我曾尝试使用event.preventDefault()return false Both are successful in stopping the form from submitting but both fail in form validation.两者都成功阻止了表单提交,但都在表单验证中失败。 I have also tried this solution , but even that does not work.我也试过这个解决方案,但即使这样也不起作用。

Is anybody able to help me?有人可以帮助我吗?

Both event.preventDefault() and return false; event.preventDefault()return false; work if used on form submit.如果在表单提交上使用,则工作。 The HTML 5 validation is still present. HTML 5 验证仍然存在。

 jQuery("form").submit(function(e){ e.preventDefault(); //or //return false; });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form action="" method="post"> <input id="name" type="text" required="required" /> <input id="email" type="email" required="required" /> <input type="submit" id="btnSubmit" /> </form>

I use checkValidity() and reportValidity() to solve this problem.我使用checkValidity()reportValidity()来解决这个问题。

Assume your form has id as FORM_ID假设您的表单的 id 为FORM_ID

Sample code:示例代码:

function handleSubmit (e) {
  e.preventDefault(); 
  var ele = document.getElementById("FORM_ID");
  var chk_status = ele.checkValidity();
  ele.reportValidity();
  if (chk_status) {
    ...
    // do your customized submit operations here.  
  }
}

reference 参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM