我在我的应用程序中有这个表单,我将通过AJAX提交它,但我想使用HTML5进行客户端验证。因此,我希望能够强制表单验证,也许通过jQuery。
我想在不提交表单的情况下触发验证。这可能吗?
我在我的应用程序中有这个表单,我将通过AJAX提交它,但我想使用HTML5进行客户端验证。因此,我希望能够强制表单验证,也许通过jQuery。
我想在不提交表单的情况下触发验证。这可能吗?
当前回答
这是让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...
}
其他回答
我认为这是最好的方法
将使用jQuery验证插件,使用最佳实践的表单验证,它也有良好的浏览器支持。因此,您不必担心浏览器兼容性问题。
并且我们可以使用jQuery验证valid()函数来检查所选表单是否有效,或者是否所有所选元素都有效,而无需提交表单。
<form id="myform">
<input type="text" name="name" required>
<br>
<button type="button">Validate!</button>
</form>
<script>
var form = $( "#myform" );
form.validate();
$( "button" ).click(function() {
console.log( "Valid: " + form.valid() );
});
</script>
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
显然,这必须在由事件侦听器调用的函数中才有意义。
要检查某个字段是否有效,请使用:
$('#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验证。
$(document).on("submit", false);
submitButton.click(function(e) {
if (form.checkValidity()) {
form.submit();
}
});
我有一个相当复杂的情况,我需要多个提交按钮来处理不同的事情。例如“保存”和“删除”。
其基础是它也不显眼,所以我不能只是让它成为一个普通的按钮。但也想利用html5验证。
此外,如果用户按下enter键触发预期的默认提交,提交事件将被覆盖;在本例中保存。
这里是处理表单的努力,使用/不使用javascript和html5验证,同时使用提交和单击事件。
jsFiddle演示- HTML5验证提交和点击覆盖
xHTML
<form>
<input type="text" required="required" value="" placeholder="test" />
<button type="submit" name="save">Save</button>
<button type="submit" name="delete">Delete</button>
</form>
JavaScript
//wrap our script in an annonymous function so that it can not be affected by other scripts and does not interact with other scripts
//ensures jQuery is the only thing declared as $
(function($){
var isValid = null;
var form = $('form');
var submitButton = form.find('button[type="submit"]')
var saveButton = submitButton.filter('[name="save"]');
var deleteButton = submitButton.filter('[name="delete"]');
//submit form behavior
var submitForm = function(e){
console.log('form submit');
//prevent form from submitting valid or invalid
e.preventDefault();
//user clicked and the form was not valid
if(isValid === false){
isValid = null;
return false;
}
//user pressed enter, process as if they clicked save instead
saveButton.trigger('click');
};
//override submit button behavior
var submitClick = function(e){
//Test form validitiy (HTML5) and store it in a global variable so both functions can use it
isValid = form[0].checkValidity();
if(false === isValid){
//allow the browser's default submit event behavior
return true;
}
//prevent default behavior
e.preventDefault();
//additional processing - $.ajax() etc
//.........
alert('Success');
};
//override submit form event
form.submit(submitForm);
//override submit button click event
submitButton.click(submitClick);
})(jQuery);
使用Javascript的警告是,浏览器默认的onclick必须传播到submit事件must发生,以便在不支持您的代码中的每个浏览器的情况下显示错误消息。 否则,如果点击事件被event. preventdefault()覆盖或返回false,它将永远不会传播到浏览器的提交事件。
需要指出的是,在某些浏览器中,当用户按下回车键时,不会触发表单提交,而是触发表单中的第一个提交按钮。因此有一个console.log('form submit')来显示它没有触发。