我在我的应用程序中有这个表单,我将通过AJAX提交它,但我想使用HTML5进行客户端验证。因此,我希望能够强制表单验证,也许通过jQuery。
我想在不提交表单的情况下触发验证。这可能吗?
我在我的应用程序中有这个表单,我将通过AJAX提交它,但我想使用HTML5进行客户端验证。因此,我希望能够强制表单验证,也许通过jQuery。
我想在不提交表单的情况下触发验证。这可能吗?
当前回答
您不需要jQuery来实现这一点。在你的表单中添加:
onsubmit="return buttonSubmit(this)
或JavaScript:
myform.setAttribute("onsubmit", "return buttonSubmit(this)");
在buttonSubmit函数(或任何调用它的函数)中,可以使用AJAX提交表单。buttonSubmit只会在你的表单在HTML5中被验证时被调用。
如果这有助于任何人,这是我的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;
}
我的一些表单包含多个提交按钮,因此这一行if (submitvalue == e.elements[i].value)。我使用单击事件设置了submitvalue的值。
其他回答
var $myForm = $('#myForm ');
if (!$myForm[0].checkValidity()) {
$('<input type="submit">').hide().appendTo($myForm).click().remove();
}
2022香草JS解决方案
纯JavaScript提供了所需的所有函数。我知道这个问题是关于jQuery的,但即使是jQuery的答案也使用了这些函数,即checkValidity()和reportValidity()。
测试整个表单
let form = document.getElementById('formId');
// Eventlistener can be another event and on another DOM object this is just an example
form.addEventListener('submit', function (event) {
// Only needed if event is submit, otherwise this line can be skipped
event.preventDefault();
// This is the important part, test if form is valid
if (form.checkValidity() === false){
// This is the magic function that displays the validation errors to the user
form.reportValidity();
return;
}
// Code if all fields are valid; continue form submit or make Ajax call.
})
测试特定领域
checkValidity()和reportValidity()不仅可以在表单上使用,还可以在特定的字段上使用。如果不需要,不需要创建表单或虚拟提交按钮。
// Get field of interest
let inputElement = document.querySelector("[name='" + inputName + "']");
// Check if the element is valid
if (inputElement.checkValidity() === false){
// If not, show the errors to the user
inputElement.reportValidity();
return;
}
// Nothing? Great, continue to the Ajax call or whatever
显然,这必须在由事件侦听器调用的函数中才有意义。
这是让HTML5对任何表单执行验证的一种非常直接的方式,同时仍然拥有对表单的现代JS控制。唯一需要注意的是提交按钮必须在<form>内。
html
<form id="newUserForm" name="create">
Email<input type="email" name="username" id="username" size="25" required>
Phone<input type="tel" id="phone" name="phone" pattern="(?:\(\d{3}\)|\d{3})[- ]?\d{3}[- ]?\d{4}" size="12" maxlength="12" required>
<input id="submit" type="submit" value="Create Account" >
</form>
js
// bind in ready() function
jQuery( "#submit" ).click( newAcctSubmit );
function newAcctSubmit()
{
var myForm = jQuery( "#newUserForm" );
// html 5 is doing the form validation for us,
// so no need here (but backend will need to still for security)
if ( ! myForm[0].checkValidity() )
{
// bonk! failed to validate, so return true which lets the
// browser show native validation messages to the user
return true;
}
// post form with jQuery or whatever you want to do with a valid form!
var formVars = myForm.serialize();
etc...
}
要检查某个字段是否有效,请使用:
$('#myField')[0].checkValidity(); // returns true|false
要检查表单是否有效,请使用:
$('#myForm')[0].checkValidity(); // returns true|false
如果你想显示某些浏览器(如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();
}
请记住,到目前为止,并不是所有浏览器都支持HTML5验证。
你说的是两种不同的东西“HTML5验证”和使用javascript/jquery的HTML表单验证。
HTML5“拥有”用于验证表单的内置选项。例如在字段上使用“required”属性,如果不使用javascript/jquery,表单提交可能会失败(基于浏览器实现)。
使用javascript /jquery,你可以做这样的事情
$('your_form_id').bind('submit', function() {
// validate your form here
return (valid) ? true : false;
});