15

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?

2
  • You could throw it in a .each() statement maybe? Commented Sep 4, 2013 at 1: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. Commented Sep 4, 2013 at 1:56

3 Answers 3

31

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/

Sign up to request clarification or add additional context in comments.

3 Comments

is there some parameters limit for this?
@Limon, no limit on the number of parameters that I am aware.
@user2956826 is right - changing adults/children fields does not re-validate attendees.
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();
});

1 Comment

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.
-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"                
    }               
});

1 Comment

There is no such method or rule called equal.

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.