2

I am using jquery-validate and I am trying to validate that the value of two fields (participants_adults and participats_child) is greater than X (a number). As an additional challenge, the second field (participats_child) may or may not exist, so if it does not exist the validation should only take the first field (participats_adults) into account.

I have this html:

<select name="participants_adults" class="valid">
   <option>1</option>
   <option>2</option>
   <option>3</option>
</select>

<select name="participants_child" class="valid">
   <option>0</option>
   <option>1</option>
   <option>2</option>
</select>

And the jQuery code I have so far is this:

<script>
 $(document).ready(function(){

 $('#booking_form').validate({
    rules: {
      participants_adults: {
        required: {
               depends: function(element) {
                return (parseInt($('[name="participants_adults"]').val()) + parseInt($('[name="participants_child"]').val()) > 2);
                 }
               }
      }
    }
   });
 });

I am not being successful at achieving this validation. Anybody can help, please?

Many thanks in advance!

Migsy
  • 43
  • 2
  • 5

1 Answers1

2

Rather than a conditional rule, create a custom method using addMethod as per the documentation.

jQuery.validator.addMethod("myMethod", function(value, element, params) {
    // your function
    // return false to display the error message
    // return true to pass validation
}, "this is the error message");

The function's arguments are defined as follows:

value
Type: String
the current value of the validated element

element
Type: Element
the element to be validated

params
Type: String
parameters specified for the method, e.g. for min: 5, the parameter is 5, for range: [1, 5] it’s [1, 5]


Also see these answers for more examples:

https://stackoverflow.com/a/19096923/594235

https://stackoverflow.com/a/15594795/594235

Community
  • 1
  • 1
Sparky
  • 98,165
  • 25
  • 199
  • 285