javascript - jquery validation plugin rules with condition? -
i using jquery validation plugin , have big form "save","submit" buttons. have 2 sets of rules 2 buttons.
- whenever user clicks save button valid rulesone set of rules (mandatory fields email, password).
- whenever user clicks save button valid rulestwo set of rules (all required fields).
any 1 suggest please, how develop ?
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 validations) { settwo rules test ? }
thanks prasad
you cannot dynamically turn validation on/off any/all parts of form plugin.
however, can use the .rules()
method dynamically add, remove, or over-ride rules @ time, giving similar behavior.
then can use the .valid()
method test form.
put them each inside dedicated click
event handlers.
$(document).ready(function() { // initialize plugin $("#form1").validate({ ignore : '*:not([name]),:hidden' // no rules; rules set dynamically below }); // save button $('#save_button').on('click', function() { // dynamically set rules $('input[name="email"]').rules('add', { required: true, .... }); // remove rules other fields $('input[name="city"]').rules('remove'); // force test of form $("#form1").valid(); }); // submit button $('#submit_button').on('click', function() { // dynamically set rules $('input[name="city"]').rules('add', { required: true, .... }); // remove rules other fields $('input[name="email"]').rules('remove'); // force test of form $("#form1").valid(); }); });
proof-of-concept demo: http://jsfiddle.net/x6ywm/
if have many fields, can make easier setting appropriate classes on them .ruleset1
, .ruleset2
. can target them group .rules()
method. remember you'll need enclose them inside jquery .each()
if selector targets more 1 element...
$('.ruleset1').each(function() { // target multiple elements $(this).rules('add', { // apply rules each required: true, .... }); });
Comments
Post a Comment