Obsolete notice:
This answer refers to an extremely old version of the jQuery.validate() plugin (version 1.5) and is now obsolete as the plugin provides an official API for solving this problem. See the .rules()
documentation for the current approach to solving this. I'm leaving this answer as-is to help anyone who must maintain a legacy site that is unable to upgrade to the latest versions of jQuery and jQuery.validate().
This uses a feature of the validator that is not well documented in the API (and by this I mean it isn't documented at all), however since it is a fundamental part of how the validator works, it is not likely to be removed even if it is undocumented.
Once you've initialized the jQuery validator, you can get access to the validator object again by calling the validate()
method on the form object you applied the validator to. This validator object has a settings
property, which stores the default settings, combined with the settings you applied to it in initialization.
Assuming I initialize the validator like this:
$('form').validate({
rules: {
leftform_input1: { required: true },
leftform_input2: { required: true }
},
messages: {
leftform_input1: "Field is required",
leftform_input2: "Field is required"
}
});
I can then get those exact settings out of the validator by doing the following:
var settings = $('form').validate().settings;
I can then easily work with this settings object to add or remove validators for the form.
This is how you would remove validation rules:
var settings = $('form').validate().settings;
delete settings.rules.rightform_input1;
delete settings.messages.rightform_input1;
And this is how you would add validation rules:
var settings = $('form').validate().settings;
settings.rules.leftform_input1 = {required: true};
settings.messages.leftform_input1 = "Field is required";
Here is a working solution for the scenario in my question. I use jQuery's extend()
method to overwrite the rules
and messages
properties of the validate
object, which is how I toggle between the two panels.
$('#toggleSwitch').click(function() {
var settings = $('form').validate().settings;
var leftForm = $('#leftform');
var rightForm = $('#rightform');
if (leftForm.css("visibility") !== "hidden") {
leftForm.css("visibility", "hidden");
rightForm.css("visibility", "visible");
$.extend(settings, {
rules: {
rightform_input1: { required: true },
rightform_input2: { required: true }
},
messages: {
rightform_input1: "Field is required",
rightform_input2: "Field is required"
}
});
} else {
rightForm.css("visibility", "hidden");
leftForm.css("visibility", "visible");
$.extend(settings, {
rules: {
leftform_input1: { required: true },
leftform_input2: { required: true }
},
messages: {
leftform_input1: "Field is required",
leftform_input2: "Field is required"
}
});
}
});