I'm trying to do initial validation before using $.ajax() call (where additional validation is performed) to save on calls to the server. Currently I'm using the following :
$('.form_submit').submit(function() {
var frm = $(this);
var url = frm.attr('action');
var data = $(this).serializeArray();
var proceed = true;
$.each(data, function(index, value) {
var name = data[index].name;
if ($('#' + name).hasClass('required') && value == '') {
$('.label_' + name).append('Please pr开发者_开发知识库ovide the value');
proceed = false;
}
});
if (proceed) {
$.ajax({
but the value of the 'proceed' variable doesn't seem to be taken under consideration and the validation goes straight to ajax.
Any help would you much appreciated.
I've figured out how to achieve it and add support for all other fields as well (such as radio buttons, textareas etc.) - here's what I've come up with:
$('.form_submit').submit(function() {
$('.warn').remove();
var frm = $(this);
var url = frm.attr('action');
var data = $(this).serializeArray();
var radios = frm.find('input:radio');
var checks = frm.find('input:checkbox');
var proceed = true;
$.each(radios, function(index, value) {
var elem = frm.find('input[name='+radios[index].name+']');
if (elem.hasClass('required') && $("input:radio[name="+radios[index].name+"]:checked").length == 0) {
var val = elem.attr('title');
if ($('.label_' + radios[index].name).find('.warn').length == 0) {
$('.label_' + radios[index].name).append('<span class="warn">'+val+'</span>');
}
proceed = false;
}
});
$.each(checks, function(index, value) {
var elem = frm.find('input[name='+checks[index].name+']');
if (elem.hasClass('required') && $("input[name="+checks[index].name+"]:checked").length == 0) {
var val = elem.attr('title');
$('.label_' + checks[index].name).append('<span class="warn">'+val+'</span>');
proceed = false;
}
});
$.each(data, function(index, value) {
var elem = frm.find('[name='+data[index].name+']');
var elem_type = elem.prop('nodeName');
if (elem.hasClass('required') && elem.val() === '') {
var val = elem.attr('title');
$('.label_' + data[index].name).append('<span class="warn">'+val+'</span>');
proceed = false;
}
});
if (proceed == true) {
$.ajax({ // here start server side validation
I've assigned the validation message to the 'title' attribute of the 'input' field - so that you can have a different one for each tag. With radio buttons - simply add 'title' to the first button.
精彩评论