14

I have 3 input fields that ask for the number of people, and of them how many are adults and how many are children. I am trying to use jQuery validate plugin to add a custom method where children + adults = number of people

This is my validation call

$("#form2").validate({
    errorElement: "span",
        rules: {
        attendees: {
             required: true,
             digits: true
        },              
        adults: {
             required: true,
             digits: true
        },              
        children: {
             required: true,
             digits: true
        }
    },
    messages: {
        attendees: "Enter the number of persons (including yourself)", 
        adults: "Enter number of adults", 
        children: "Enter number of childern"                
    }               
});

I looked at the group feature and .addMethod() method of the validate plugin but it seems that it was crafted only with one element in mind. Any ideas?

Sparky
  • 98,165
  • 25
  • 199
  • 285
Faiyet
  • 5,341
  • 14
  • 51
  • 66
  • You could throw it in a `.each()` statement maybe? – Sterling Archer Sep 04 '13 at 01:40
  • 1
    I would suggest, completely skip the attendees input if you want to put a restriction that total = adult + children. Instead, have a hidden field "total" the value for which should be updated to children + adult just before the form is submitted. – Neeraj Sep 04 '13 at 01:56

3 Answers3

29

Follow the documentation for creating a custom method/rule. Here, I simply call it totalCheck, but you can name it anything you wish.

$.validator.addMethod('totalCheck', function(value, element, params) {
    var field_1 = $('input[name="' + params[0] + '"]').val(),
        field_2 = $('input[name="' + params[1] + '"]').val();
    return parseInt(value) === parseInt(field_1) + parseInt(field_2);
}, "Enter the number of persons (including yourself)");

It's implemented just like any other rule. The two parameters are the name attributes of the two other fields you want to check against. Since this new rule says the field must contain the sum of the two other fields, the required and digits rules are now redundant and can be removed.

$("#form2").validate({
    errorElement: "span",
    rules: {
        attendees: {
            totalCheck: ['adults', 'children'] // <-- your custom rule
        },
        adults: {
            required: true,
            digits: true
        },
        children: {
            required: true,
            digits: true
        }
    },
    messages: {
        adults: "Enter number of adults",
        children: "Enter number of childern"
    }
});

Working DEMO: http://jsfiddle.net/hBXL6/


EDIT:

Added a keyup focusout handler to re-validate attendees whenever other fields are changed. These are the same two default event handlers used by the plugin.

$('input[name="adults"], input[name="children"]').on('keyup focusout', function() {
    $('input[name="attendees"]').valid();
});

New working DEMO: http://jsfiddle.net/ua0534dv/2/

Sparky
  • 98,165
  • 25
  • 199
  • 285
2

The answer by Sparky is not complete: the adults and children need to re-validate attendees when changed.

Append this at the end:

$('input[name=adults],input[name=children]').on('change', function(){
  $('input[name=attendees]').removeData("previousValue").valid();
});
Sparky
  • 98,165
  • 25
  • 199
  • 285
leobard
  • 41
  • 4
  • I incorporated your idea into my answer. No need for `removeData()` since nothing in this code has been set with `.data()`; and should be `keyup` and `focusout` so you get dynamic validation just like the plugin's defaults. – Sparky Jul 19 '19 at 20:11
-1

As suggested in comments this is not a good practice. Nonetheless, if you still want to do it:

$("#form2").validate({
    errorElement: "span",
        rules: {
        attendees: {
             equal: $("#form2 #adults").val() + $("#form2 #children").val();
        },              
        adults: {
             required: true,
             digits: true
        },              
        children: {
             required: true,
             digits: true
        }
    },
    messages: {
        attendees: "Enter the number of persons (including yourself)", 
        adults: "Enter number of adults", 
        children: "Enter number of childern"                
    }               
});
Neeraj
  • 8,408
  • 8
  • 41
  • 69