我编写了一个脚本,它允许我使用 Zend_Form 验证器验证表单,而不是经典的客户端验证(如 jQuery Validate)+ 服务器端验证。
$(document).ready(function() {
var form = $('form'); // target form
var requests = [], validations = [];
var nbInputs = $('input[type="text"], input[type="password"]').length; // number of inputs (text/password) in the form
var cancelSubmit = true;
form.submit(function() {
// if we call the submit inside the function, skip validation
if(cancelSubmit === false) {
console.log('[-] cancelSubmit is false. Validation skipped.');
return true;
}
console.log('[-] Entering validation');
// resetting requests and validations results
requests.length = 0;
validations.length = 0;
// for each input (text/password), get the validation status from the server
$('input[type="text"], input[type="password"]').each(function(i) {
var validatorField = $(this).attr('data-validator');
var valueField = $(this).val();
postData = {
validator: validatorField,
value: valueField
};
// storing requests into an array
requests.push($.post('/validate', postData));
});
(function($) {
$.whenAll = function() {
return $.when.apply($, arguments);
};
})(jQuery);
// when all the requests are done and returned a response
$.whenAll(requests).then(function() {
// show the validation status for each input
$.each(requests, function(i, element) {
element.done(function(data) {
json = $.parseJSON(data);
formGroup = $('input:eq('+i+')').parent();
// if it isn't valid, show error
if(json.valid == 0) {
if($('span.help-block', formGroup).length == 0) {
$(formGroup).addClass('has-error').append('<span class="help-block">'+json.message+'</span>');
$('label', formGroup).addClass('control-label');
}
// and store the validation status
validations.push(0);
}
// else, remove error
else if(json.valid == 1) {
$(formGroup).removeClass('has-error');
$('.help-block', formGroup).remove();
// and store the validation status
validations.push(1);
}
// if we got all the validations required
if(validations.length == nbInputs)
{
console.log('[-] All validations have been done.');
if($.inArray(0, validations) == -1){
console.log('[-] No errors. Submitting form.');
cancelSubmit = false;
form.submit();
}
else
console.log('[-] There are still errors.');
}
});
});
});
return false;
});
});
验证页面服务器端发送 JSON :{ valid: 0, message: "error message" }
或{ valid: 1}
.
我无法提交表单。当我输入有效值时,它会跳过验证,但不提交表单。我必须再次点击提交按钮才能使其工作(但是,我可能输入了这次不会检查的无效值,如cancelSubmit
设置为false
)。
在 a 中使用时不return true;
应该提交表单.submit()
吗?