我正在使用jquery验证插件,我有以下代码进行验证,这是一个令人不安的问题,它只是一个规范,我希望错误应该显示在屏幕上
jQuery(document).ready(function() {
jQuery('form.CWvalidate').each(function() {
var alertID = jQuery(this).attr('id');
jQuery(this).prepend('<div class="CWalertBox alertText validationAlert" style="display:none;"></div><div class="CWclear"></div>');
});
jQuery('form.CWvalidate select').change(function() {
jQuery(this).blur();
});
jQuery.validator.setDefaults({
focusInvalid: true,
onkeyup: false,
onblur: true,
errorClass: "warning",
errorElement: "span",
errorPlacement: function(error, element) {
jQuery(element).siblings('label').addClass('warning');
},
showErrors: function(errorMap, errorList) {
if (this.numberOfInvalids() > 0) {
var formID = jQuery(this.currentForm).attr('id');
if (formID == 'CWformCustomer') {
var validationMessage = 'Complete all required information';
} else if (formID == 'CWformLogin') {
var validationMessage = '';
} else if (formID == 'CWformOrderSubmit') {
var validationMessage = 'Complete all required information';
} else if (formID == 'CWformAddToCartWindow') {
var validationMessage = 'Select at least one item';
} else if (formID == 'CWformAddToCart') {
var validationMessage = 'Choose from below options before adding to cart';
} else {
var validationMessage = 'Complete your selection';
};
if (!(validationMessage == '')) {
jQuery(this.currentForm).find('.errormsg').show().html(validationMessage);
};
this.defaultShowErrors();
} else {
jQuery(this.currentForm).children('div.validationAlert').empty().hide();
jQuery(this.currentForm).children('span.warning').remove();
jQuery(this.currentForm).children('.warning').removeClass('warning');
}
}
});
jQuery('form.CWvalidate').each(function() {
jQuery(this).validate();
});
});
但是每当我使用这个类CWvalidate
时,表单都会验证,但表单的提交处理程序不会像下面的代码那样使用它:
$("#dataModification").validate({
submitHandler: function(form) {
var datastring = $(form).serialize();
$.ajax({
type:"post",
url: 'xyz.cfm',
data: datastring,
success: function(data) {
var obj = $.trim(data);
if (obj == 'success'){
parent.$.fancybox.close();
}else{
alert(obj);
}
}
});
}
});
出了什么问题我被困住了,不知道发生了什么......
答案 0 :(得分:0)
您似乎在同一表单上两次致电.validate()
...
下面:
jQuery(document).ready(function() {
....
jQuery('form.CWvalidate').each(function() {
jQuery(this).validate();
});
});
在这里:
$("#dataModification").validate({
submitHandler: function(form) {
...
仅使用第一个实例,并忽略任何后续实例,这解释了为什么submitHandler
无效并且表单只是刷新。它还解释了为什么它只在使用CWvalidate
类时失败。
要解决此问题,您必须弄清楚如何为每个表单调用.validate()
一个时间。
一种可能的解决方法是将您的ajax网址放在action
标记的form
属性中,然后使用.ajax()
在.attr('action')
内检索此网址。然后,您的submitHandler
可以通用,可以包含在setDefaults()
中。
submitHandler: function(form) {
var datastring = $(form).serialize();
$.ajax({
type: "post",
url: $(form).attr('action'), ...
另请注意:此插件没有名为onblur
的选项。它是onfocusout
,您无法在不破坏插件的情况下将其设置为true
。 It can only be set to false
or a function