Add jQuery validation rule to radio button group

I am using jQuery Validation Plugin and I want to be able to dynamically add and remove validation from 3 groups of radio buttons.

I can dynamically add and remove confirmation from text box input using the sample code below:

<script type="text/javascript"> $(document).ready(function(){ //Add Requird Validation $("#inputTextField").rules("add", "required"); //Remove Required Validation $("#inputTextField").rules("remove", "required"); }); </script> 

Is it possible to do the same with radio buttons?

+4
source share
2 answers

The code you posted will work fine. However, rules('add') should appear after .validate() , and each input must contain the name attribute, even if you don't target name .

HTML

 <form id="myform"> <input type="text" name="field" id="inputTextField" /> <br/> </form> 

JQuery

 $(document).ready(function() { $('#myform').validate({ // other options & rules }); // must come afer validate() $("#inputTextField").rules("add", { required: true }); }); 

Demo: http://jsfiddle.net/fnKWD/

Is it possible to do the same with radio buttons?

Of course, just specify them by name or any other valid jQuery selector .

 $('input[name="myname"]') 

HTML

 <input type="radio" name="myname" value="0" /> <input type="radio" name="myname" value="2" /> <input type="radio" name="myname" value="5" /> 

Demo : http://jsfiddle.net/LkJZw/

+3
source

You can use the required method with a dependency expression . Here you specify the required rule, for example

 rules: { details: { required: "#other:checked" } } 

this can be useful sometimes in that you don't need to add or remove rules to get conditional validation on your elements. Try an example in jsfiddle

0
source

All Articles