What I have set up is a big form with two main pieces. The first piece the user is filling out some basic info. The second piece the user is adding some 'sizing' options, which there could be multiples of. The sizing info is filled out in a panel and then 'saved', cloning the form elsewhere and then wiping the panel for another size to be added. When this 'save' takes place, I fire validation for only that portion of the form.
$.validator.addMethod("pageRequired", function(value, element) {
if (valid_distributions > 0) {
$('#distributor-select').prop('required', false)
}
if (current_page == 1) {
return this.optional(element);
}else if (current_page == 2) {
return !this.optional(element);
} else {
return "dependency-mismatch";
}
}, $.validator.messages.required)
This chunk is what switched the requirement of the first half of the form. Basically, I am getting some glitchy behavior where sometimes I can validate just the bottom of the form, but othertimes Jquery is being told to validate the whole form when saving just the bottom.
I know my condition for the elements being required or not is firing, yet still they are being required.
var v = $("#beer-create-form").validate({
debug: true,
rules: {
'keg_sizes[]': {
required: true
}
},
messages: {
'keg_sizes[]': 'Choose at least one keg size'
},
errorClass: "error",
errorPlacement: function (error, element) {
if (element.hasClass('kegsize-toggle')){
error.insertAfter(element.parents().find('.distributor-name'));
}else if (element.hasClass('price')) {
console.log('price');
}
},
highlight: function(element, errorClass) {
$(element).addClass(errorClass);
},
unhighlight: function(element, errorClass) {
$(element).removeClass(errorClass);
}
});
$(document).on('click', '.save-listing', function(e) {
current_page = 1;
if (v.form()) { // if the form is valid, proceed to:
saveBeerPanel(); //clones the panel being filled out with all the info
wipeBeerPanel(); // clears all the info previously filled out so a new listing can be added
valid_distributions += 1 // keeps track that there is at least one valid distribution
}
e.preventDefault();
});
I tried changing the 'required' switch with this code:
if (current_page == 1) {
console.log('top is optional');
return $(element).prop('required', false)
}else if (current_page == 2) {
return $(element).prop('required', true)
} else {
return "dependency-mismatch";
}
... but that doesn't seem to help.
Why are those elements not being changed to optional or not?
Working fiddle demonstrates how the form should work: http://jsfiddle.net/hodale/0c41465t/
Also, here is the demo I was using for inspiration: http://jsfiddle.net/hodale/aqpyykt0/