Removing jQuery validation on the fly
I'm trying to rule out the jQuery Validation plugin from being able to validate if a specific form option (phone only) is selected using $ ("# form_id"). rules ("remove", "required"); but it doesn't work ...
All I get is a javascript error when I select only phone: "TypeError: The result of the expression" F "[undefined] is not an object and the form won't submit as it still validates required fields.
//field validation
$('#location').change(function(){
location_val = $('#location').val();
if (location_val == "select") {
$('.hide').hide();
}
else if (location_val == "my_location") {
$('.hide').hide();
$('#f_address, #f_address2, #f_city, #f_state_zip, #f_phone').customFadeIn('fast');
$("#step2").rules("add", "required");
}
else if (location_val == "customers_location") {
$('.hide').hide();
$('#f_area, #f_phone, #f_city, #f_state_zip').customFadeIn('fast');
$("#step2").rules("add", "required");
}
else if (location_val == "both") {
$('.hide').hide();
$('#f_area, #f_address, #f_address2, #f_city, #f_state_zip, #f_phone').customFadeIn('fast');
$("#step2").rules("add", "required");
}
else if (location_val == "phone") {
$('.hide').hide();
$('#f_phone').customFadeIn('fast');
$("#step2").rules("remove", "required");
}
});
$("#step2").validate({
rules: {
city: {required: true},
state: {required: true},
zip: {required: true}
}
});
Understanding is appreciated.
source to share
The way I accomplished this task is to use a CSS class that is different from the set of validation rules. Therefore, for fields that are usually "required", I generate elements with the "requirements" CSS class. Then add this to the page:
function addRequired() {
$('.requirement').each(function() {
$(this).rules("add", {required: true});
});
}
function removeRequired() {
$('.requirement').valid(); // can't remember why I have this, but it in source control now for awhile...
$('.requirement').each(function() {
$(this).rules("remove");
});
}
$(document).ready(function() {
$('form').validate({...});
addRequired();
});
then hook some behavior on the trigger element of the trigger (which looks like a radio button in your case) that, when selected, calls addRequired()
. And when he is no longer selected, call removeRequired()
. And obviously consider the different back end checkout options.
source to share