0

I need some guidance on how to add a validation method to the jquery validate plugin. I've gathered that i need to use the plugin's addMethod() function, but how exactly to have it do what i need... Here i am!

My form 's first question is a radio input choice. Each radio input, if selected, shows a sub-question of several checkboxes.

What i would like my validation to do is: - make sure one radio input is selected - make sure at least one checkbox pertaining to the radio input is selected.

Basically, out of the validate plugin's own logic, i would count the selector's length, and if there isn't any, return the error message. Something like this:

var weekSelected = ($('input.seasonSelector:checked input.weekSelector:checked',form).length > 0);
if(!weekSelected){
return 'Please select a week inside that season';
}

How to turn that into a validate plugin method ?

UPDATE

here is the successful answer, based on your feedback:

$('#newInscription').validate({
        rules: {
            "season_id": "required",
            "weeks[]": {
                required: {
                    depends: function() {
                        return $(this).parents(".seasonSelector:checked");
                    }
                }
            }
        }
        ,
...

1 Answer 1

2

Why not make the radio a required element and each of the sub-questions a required element, but dependent on the related radio? You should be able to do this by just adding rules. It will be easier if each group of checkboxes have the same name.

$("form").validate({
     rules: {
         "Season": "required",
         "SpringWeeks": {
              required: {
                   depends: function() {
                       return $(".seasonSelector:checked").val() == "Spring";
                   }
              }
         }
         ...
});

<input type="radio" name="Season" value="Spring"  />
...
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for pointing me to this clever alternative. i tried it. It currently works for the first-level question but i'm not so successful with the second-level one. Can you look at my updated code (i've added it to the question)?
nevermind, i solved it. Thanks a lot, you get the accepted answer, as you got me close enough to the solution!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.