jQuery验证blur和ajax发布的输入
我有一个由ajax处理的表单,它使用jQueryValidate进行验证。它按预期工作,但当我在表单字段的模糊上添加字段验证时,它会停止正常工作。它不再通过ajax发布,而是转到用于处理ajax的php文件。它似乎也没有正确处理文件上传,说有时没有。在发布失败后,通过浏览器返回并重新提交后,仍然可以正常工作。所以我不确定发生了什么 以下是JS:jQuery验证blur和ajax发布的输入,jquery,ajax,jquery-validate,Jquery,Ajax,Jquery Validate,我有一个由ajax处理的表单,它使用jQueryValidate进行验证。它按预期工作,但当我在表单字段的模糊上添加字段验证时,它会停止正常工作。它不再通过ajax发布,而是转到用于处理ajax的php文件。它似乎也没有正确处理文件上传,说有时没有。在发布失败后,通过浏览器返回并重新提交后,仍然可以正常工作。所以我不确定发生了什么 以下是JS: // highlight input fields on blur - This is what stops it working $(
// highlight input fields on blur - This is what stops it working
$('.input-field').on('focusout', function(){
$(this).parents('form').validate({
onfocusout: function(element) {
this.element(element);
},
onkeyup: false
});
});
// Ajax form submit/validation
$(document).on('click', '.form-submit', function(e){
// Whichever form sent it..
var $thisForm = $(this).parents('form');
// Validate it...
$thisForm.validate({
ignore: '',
rules: {
upload: {
required: true
}
},
submitHandler: function(form) {
var formData = new FormData($thisForm[0]);
// Show the loading spinner
$thisForm.addClass('loading').find('.padded').remove();
e.preventDefault();
$.ajax({
type: "POST",
dataType: "json",
data: formData,
processData: false,
contentType: false,
url: $thisForm.attr('action'),
success: function(data) {
// When we're done, remove spinner and add the thank you message
$thisForm.parents('aside').addClass('textcenter padded').html(data.message);
$('.loading').removeClass('loading');
}
});
}
});
});
你的代码
// highlight input fields on blur - This is what stops it working
$('.input-field').on('focusout', function(){
$(this).parents('form').validate({....
而这个
// Ajax form submit/validation
$(document).on('click', '.form-submit', function(e){
....
// Validate it...
$thisForm.validate({ ....
.validate()
不能像您所做的那样将其与初始化选项一起附加到单个字段
您完全误解了.validate()
方法的目的.validate()
只是初始化表单上插件的方法。这不是测试的方法。测试是自动执行的,因为插件正在捕获按钮的点击和各种其他事件,以便自动触发
您永远不会将.validate()
放在焦点输出
或单击
处理程序中。根据此插件的默认设置,“聚焦输出”和“单击”时自动触发验证
您只需要正确地初始化它
$(document).ready(function() { // DOM is loaded
$('.forms').each(function() { // select all forms
$(this).validate({ // initialize plugin on each form
// options // your plugin options
});;
});
});
进入DOM ready偶数处理函数的内部,以便在页面加载时初始化插件.validate()
- 当
一次附加到多个表单时,就像使用类选择器一样,该方法只对第一个匹配的元素起作用。您需要使用jQuery.validate()
来解决这个问题.each()