如何强制HTML5表单验证,而不通过jQuery提交 [英] How to force a html5 form validation without submitting it via jQuery

查看:116
本文介绍了如何强制HTML5表单验证,而不通过jQuery提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用中使用了这种形式,我将通过AJAX提交它,但我想使用HTML5进行客户端验证。所以我希望能够通过jQuery强制进行表单验证。

I have this form in my app and I will submit it via AJAX, but I want to use HTML5 for client-side validation. So I want to be able to force the form validation, perhaps via jQuery.

我想在不提交表单的情况下触发验证。是否有可能?

I want to trigger the validation without submitting the form. Is it possible?

推荐答案

要检查某个字段是否有效,请使用:

To check whether a certain field is valid, use:

$('#myField')[0].checkValidity(); // returns true/false

要检查表单是否有效,请使用:

To check if the form is valid, use:

$('#myForm')[0].checkValidity(); // returns true/false

如果您想显示某些浏览器的本机错误消息(例如作为Chrome浏览器),不幸的是唯一的方法是提交表单,如下所示:

If you want to display the native error messages that some browsers have (such as Chrome), unfortunately the only way to do that is by submitting the form, like this:

var $myForm = $('#myForm');

if(! $myForm[0].checkValidity()) {
  // If the form is invalid, submit it. The form won't actually submit;
  // this will just cause the browser to display the native HTML5 error messages.
  $myForm.find(':submit').click();
}

希望这会有所帮助。请记住,所有浏览器都不支持HTML5验证。

Hope this helps. Keep in mind that HTML5 validation is not supported in all browsers.

这篇关于如何强制HTML5表单验证,而不通过jQuery提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆