jQuery validate across multiple fields

后端 未结 3 1423
天涯浪人
天涯浪人 2020-12-14 11:54

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

3条回答
  •  独厮守ぢ
    2020-12-14 12:14

    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/

提交回复
热议问题