[英]issues with jquery validate plugin
我正在使用一个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 CWvalidate
,表单都会验证,但表单的submithandler不会像我在下面的代码中那样使用它:
$("#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);
}
}
});
}
});
有什么问题我被困住了,不知道发生了什么......
你似乎在同一个表单上两次调用.validate()
...
这里:
jQuery(document).ready(function() {
....
jQuery('form.CWvalidate').each(function() {
jQuery(this).validate();
});
});
和这里:
$("#dataModification").validate({
submitHandler: function(form) {
...
仅使用第一个实例,并忽略任何后续实例,这解释了为什么您的submitHandler
无法正常工作且表单只是刷新。 它还解释了为什么它只在使用CWvalidate
类时失败。
为了解决这个问题,你就必须弄清楚如何调用.validate()
每每个窗体一次 。
一种可能的解决方法是将ajax URL放在form
标签的action
属性中,然后使用.attr('action')
在.ajax()
检索此URL。 然后你的submitHandler
可以足够通用,可以包含在setDefaults()
。
submitHandler: function(form) {
var datastring = $(form).serialize();
$.ajax({
type: "post",
url: $(form).attr('action'), ...
另请注意:此插件没有名为onblur
选项。 它是onfocusout
,你不能在不破坏插件的情况下将其设置为true
。 它只能设置为false
或函数 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.