如何在不通过 jQuery 提交的情况下强制进行 html5 表单验证 [英] How to force a html5 form validation without submitting it via 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 验证.
Keep in mind that, HTML5 validation is not supported in all browsers till now.
这篇关于如何在不通过 jQuery 提交的情况下强制进行 html5 表单验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!