5

I'm using jQuery Validation Plugin and I want to be able to dynamically add and remove validation from 3 radio button groups.

I am able to dynamically add and remove validation from text field 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?

Sparky
  • 98,165
  • 25
  • 199
  • 285
AlGallaf
  • 627
  • 6
  • 15
  • 28
  • Have you tried to add the rule and tested it? – Ruben Infante Feb 18 '13 at 21:31
  • How can I add it? I can't use element ID as I did with the text field. – AlGallaf Feb 18 '13 at 21:38
  • 1
    You technically can use an ID assuming each of your radio inputs has a unique one. I believe to add a required state on a radio button group you just need to add it to one of them. Try it out and if it does not work, modify your question with details of what you tried and what your form looks like. – Ruben Infante Feb 18 '13 at 21:43

2 Answers2

3

The code as you've posted it will work fine. However, rules('add') must come after .validate() and each input must contain a name attribute even if you're not targeting by 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 target them by name or by 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/

Sparky
  • 98,165
  • 25
  • 199
  • 285
  • 1
    I applied the same concept to a radio button group but I ended up with the following error: Uncaught TypeError: Cannot read property 'settings' of undefined – AlGallaf Feb 18 '13 at 22:09
  • @looi76, I can't see your code so I have no idea what you're doing wrong, but it's working here: http://jsfiddle.net/LkJZw/ – Sparky Feb 18 '13 at 22:15
  • @looi76, see my edit for a working demo using `radio` buttons. – Sparky Feb 18 '13 at 23:11
0

You may consider using the the required method with a dependency expression. This is where you specify the required rule like

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

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

politus
  • 5,996
  • 1
  • 33
  • 42