Reputation: 935
I am using Jquery validation plugin , I have a big form with "Save","Submit" buttons. I have two sets of rules for two buttons.
Any one suggest please, how to develop like this ?
Set1 rules:
var rulesOne = { email : "required" .......}
Set2 rules:
var rulesTwo = {city : "required" ..........}
$("#form1").validate({
ignore : '*:not([name]),:hidden',
rules : rules});
If save button
if(this.id == "personal_save"){
setOne rules test ?
else
// submit button (check all validations)
{
setTwo rules test ?
}
Thanks Prasad
Upvotes: 1
Views: 6777
Reputation: 772
I faced to the same problem and after a lot of research I came to a solution. It consists in using JQuery.extend to replace the rules property in settings of the validator. I created a jsfiddle based on @Sparky 's one. http://jsfiddle.net/rWsLy/
$('#save_button').on('click', function () {
var settings = $("#form1").validate().settings;
// Modify validation settings
$.extend(settings, {
rules: {
field1: {
required: true,
},
},
});
// force a test of the form
$("#form1").valid();
});
I prefer this way because rules are specified in the same way as in validate method. Also I think, previous solution doesn't scale.
Upvotes: 0
Reputation: 98758
You cannot dynamically turn validation on/off for any/all parts of a form with this plugin.
However, you can use the .rules()
method to dynamically add, remove, or over-ride your rules at any time, giving you a similar behavior.
Then you can use the .valid()
method to test the form.
Put them each inside dedicated click
event handlers.
$(document).ready(function() {
// initialize the plugin
$("#form1").validate({
ignore : '*:not([name]),:hidden'
// no rules; rules are set dynamically below
});
// Save Button
$('#save_button').on('click', function() {
// dynamically set the rules
$('input[name="email"]').rules('add', {
required: true,
....
});
// remove all rules from the other fields
$('input[name="city"]').rules('remove');
// force a test of the form
$("#form1").valid();
});
// Submit Button
$('#submit_button').on('click', function() {
// dynamically set the rules
$('input[name="city"]').rules('add', {
required: true,
....
});
// remove all rules from the other fields
$('input[name="email"]').rules('remove');
// force a test of the form
$("#form1").valid();
});
});
Proof-of-concept DEMO: http://jsfiddle.net/x6YWM/
If you have many fields, you can make this easier by setting appropriate classes on them like .ruleset1
and .ruleset2
. Then you can target them as a group with the .rules()
method. Just remember that you'll need to enclose them inside a jQuery .each()
if the selector targets more than one element...
$('.ruleset1').each(function() { // target multiple elements
$(this).rules('add', { // apply the rules to each
required: true,
....
});
});
Upvotes: 2