Removing jQuery Validation on the fly
I'm trying to prevent the jQuery Validation plugin from validating if a certain form option (phone only) is selected using $("#form_id").rules("remove", "required"); feature, but it's not working...
All I get is a javascript error when I select phone only: "TypeError: Result of expression 'F' [undefined] is not an object, and the form won't submit since it's still validating 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}
}
});
Insights appreciated.
The way I accomplished this task is to use a CSS class that is different from the Validation ruleset. So for fields that are normally 'required' I am generating the elements with a 'requirement' CSS class. Then I add this in 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's in source control now for awhile...
$('.requirement').each(function() {
$(this).rules("remove");
});
}
$(document).ready(function() {
$('form').validate({...});
addRequired();
});
then hook some behavior on your triggering form element (which looks to be a radio button in your case) that when it's selected, call addRequired()
. And when it's no longer selected then call removeRequired()
. And obviously account for the different validation options on the back end.
精彩评论