如何在不通过 jQuery 提交的情况下强制进行 html5 表单验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11866910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to force a html5 form validation without submitting it via jQuery
提问by razenha
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.
我的应用程序中有这个表单,我将通过 AJAX 提交它,但我想使用 HTML5 进行客户端验证。所以我希望能够强制进行表单验证,也许是通过 jQuery。
I want to trigger the validation without submitting the form. Is it possible?
我想在不提交表单的情况下触发验证。是否可以?
回答by Abraham
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
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:
如果您想显示某些浏览器(例如 Chrome)的本机错误消息,不幸的是,唯一的方法是提交表单,如下所示:
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();
}
Hope this helps. Keep in mind that HTML5 validation is not supported in all browsers.
希望这可以帮助。请记住,并非所有浏览器都支持 HTML5 验证。
回答by Martin Christensen
I found this solution to work for me. Just call a javascript function like this:
我发现这个解决方案对我有用。只需像这样调用一个 javascript 函数:
action="javascript:myFunction();"
action="javascript:myFunction();"
Then you have the html5 validation... really simple :-)
然后你有 html5 验证......真的很简单:-)
回答by user1575761
if $("form")[0].checkValidity()
$.ajax(
url: "url"
type: "post"
data: {
}
dataType: "json"
success: (data) ->
)
else
#important
$("form")[0].reportValidity()
from: html5 form validation
来自:html5 表单验证
回答by rynop
Here is a more general way that is a bit cleaner:
这是一种更通用的方法,更简洁:
Create your form like this (can be a dummy form that does nothing):
像这样创建您的表单(可以是一个什么都不做的虚拟表单):
<form class="validateDontSubmit">
...
Bind all forms that you dont really want to submit:
绑定所有您不想提交的表单:
$(document).on('submit','.validateDontSubmit',function (e) {
//prevent the form from doing a submit
e.preventDefault();
return false;
})
Now lets say you have an <a>
(within the <form>
) that on click you want to validate the form:
现在假设您有一个<a>
(在 内<form>
),点击您想要验证表单:
$('#myLink').click(function(e){
//Leverage the HTML5 validation w/ ajax. Have to submit to get em. Wont actually submit cuz form
//has .validateDontSubmit class
var $theForm = $(this).closest('form');
//Some browsers don't implement checkValidity
if (( typeof($theForm[0].checkValidity) == "function" ) && !$theForm[0].checkValidity()) {
return;
}
//if you've gotten here - play on playa'
});
Few notes here:
这里有一些注意事项:
- I have noticed that you don't have to actually submit the form for validation to occur - the call to
checkValidity()
is enough (at least in chrome). If others could add comments with testing this theory on other browsers I'll update this answer. - The thing that triggers the validation does not have to be within the
<form>
. This was just a clean and flexible way to have a general purpose solution..
- 我注意到您不必实际提交表单以进行验证 - 调用
checkValidity()
就足够了(至少在 chrome 中)。如果其他人可以通过在其他浏览器上测试这个理论来添加评论,我会更新这个答案。 - 触发验证的东西不必在
<form>
. 这只是一种干净灵活的通用解决方案。
回答by Boopathi.Indotnet
below code works for me,
下面的代码对我有用,
$("#btn").click(function () {
if ($("#frm")[0].checkValidity())
alert('sucess');
else
//Validate Form
$("#frm")[0].reportValidity()
});
回答by vzr
May be late to the party but yet somehow I found this question while trying to solve similar problem. As no code from this page worked for me, meanwhile I came up with solution that works as specified.
聚会可能迟到了,但不知何故,我在尝试解决类似问题时发现了这个问题。由于此页面中没有任何代码对我有用,同时我想出了按规定工作的解决方案。
Problem is when your <form>
DOM contain single <button>
element, once fired, that <button>
will automatically sumbit form. If you play with AJAX, You probably need to prevent default action. But there is a catch: If you just do so, You will also prevent basic HTML5 validation. Therefore, it is good call to prevent defaults on that button only if the form is valid. Otherwise, HTML5 validation will protect You from submitting. jQuery checkValidity()
will help with this:
问题是当你的<form>
DOM 包含单个<button>
元素时,一旦被触发,<button>
就会自动提交表单。如果您使用 AJAX,您可能需要阻止默认操作。但有一个问题:如果你这样做,你也会阻止基本的 HTML5 验证。因此,只有当表单有效时,才可以防止该按钮上的默认值。否则,HTML5 验证将保护您免于提交。jQuerycheckValidity()
将帮助解决这个问题:
jQuery:
jQuery:
$(document).ready(function() {
$('#buttonID').on('click', function(event) {
var isvalidate = $("#formID")[0].checkValidity();
if (isvalidate) {
event.preventDefault();
// HERE YOU CAN PUT YOUR AJAX CALL
}
});
});
Code described above will allow You to use basic HTML5 validation (with type and pattern matching) WITHOUT submitting form.
上面描述的代码将允许您在不提交表单的情况下使用基本的 HTML5 验证(带有类型和模式匹配)。
回答by Peter Pajchl
You speak of two different things "HTML5 validation" and validation of HTML form using javascript/jquery.
您谈到了两种不同的事情“HTML5 验证”和使用 javascript/jquery 验证 HTML 表单。
HTML5 "has" built-in options for validating a form. Such as using "required" attribute on a field, which could (based on browser implementation) fail form submission without using javascript/jquery.
HTML5“具有”用于验证表单的内置选项。例如在字段上使用“必需”属性,这可能(基于浏览器实现)在不使用 javascript/jquery 的情况下使表单提交失败。
With javascrip/jquery you can do something like this
使用 javascript/jquery 你可以做这样的事情
$('your_form_id').bind('submit', function() {
// validate your form here
return (valid) ? true : false;
});
回答by Rafik malek
var $myForm = $('#myForm ');
if (!$myForm[0].checkValidity()) {
$('<input type="submit">').hide().appendTo($myForm).click().remove();
}
回答by Dan Bray
You don't need jQuery to achieve this. In your form add:
你不需要 jQuery 来实现这一点。在您的表单中添加:
onsubmit="return buttonSubmit(this)
or in JavaScript:
或在 JavaScript 中:
myform.setAttribute("onsubmit", "return buttonSubmit(this)");
In your buttonSubmit
function (or whatver you call it), you can submit the form using AJAX. buttonSubmit
will only get called if your form is validated in HTML5.
在您的buttonSubmit
函数(或任何您调用的函数)中,您可以使用 AJAX 提交表单。buttonSubmit
仅当您的表单在 HTML5 中验证时才会被调用。
In case this helps anyone, here is my buttonSubmit
function:
如果这对任何人有帮助,这是我的buttonSubmit
功能:
function buttonSubmit(e)
{
var ajax;
var formData = new FormData();
for (i = 0; i < e.elements.length; i++)
{
if (e.elements[i].type == "submit")
{
if (submitvalue == e.elements[i].value)
{
submit = e.elements[i];
submit.disabled = true;
}
}
else if (e.elements[i].type == "radio")
{
if (e.elements[i].checked)
formData.append(e.elements[i].name, e.elements[i].value);
}
else
formData.append(e.elements[i].name, e.elements[i].value);
}
formData.append("javascript", "javascript");
var action = e.action;
status = action.split('/').reverse()[0] + "-status";
ajax = new XMLHttpRequest();
ajax.addEventListener("load", manageLoad, false);
ajax.addEventListener("error", manageError, false);
ajax.open("POST", action);
ajax.send(formData);
return false;
}
Some of my forms contain multiple submit buttons, hence this line if (submitvalue == e.elements[i].value)
. I set the value of submitvalue
using a click event.
我的一些表单包含多个提交按钮,因此这一行if (submitvalue == e.elements[i].value)
。我设置了submitvalue
使用单击事件的值。
回答by Trusha Soni
To check all the required fields of form without using submit button you can use below function.
要在不使用提交按钮的情况下检查表单的所有必填字段,您可以使用以下功能。
You have to assign requiredattribute to the controls.
您必须为控件分配所需的属性。
$("#btnSave").click(function () {
$(":input[required]").each(function () {
var myForm = $('#form1');
if (!$myForm[0].checkValidity())
{
$(myForm).submit();
}
});
});