Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery validate across multiple fields

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?

like image 525
Faiyet Avatar asked Sep 04 '13 01:09

Faiyet


1 Answers

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/

like image 84
Sparky Avatar answered Sep 23 '22 05:09

Sparky