VAAA VAAA - 6 months ago 59
jQuery Question

jQuery Validate plugin one field required, but not both

I have a form that I'm validating with jQuery Validate plugin and I would like only one field to be filled out, while the other will have a 0 (zero) value. However, it must be mandatory that one or the other be filled out.

Here is my actual form:

enter image description here

This is my form HTML:

<div class="row">
<div class="col-md-6">
<div class="form-group">
<label> <span>Amount to Player</span></label>
<input name="AmountToHorse" type="text" class="form-control">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label> <span>Amount to Stable</span></label>
<input name="AmountToStable" type="text" class="form-control">
</div>
</div>
</div>


This is my validation:

$('#reloadForm').validate({
rules: {

AmountToHorse: {
required: true,
number: true
},
AmountToStable: {
required: true,
number: true
},
}
});


Any clue on how to do that?

Answer

You'll need to use the .addMethod() method to write a custom rule to ensure only one is filled out.

Adjust accordingly...

$(document).ready(function () {

    $.validator.addMethod('onlyOne', function(value, element, param) {
        return this.optional(element) || $('[name="' + param[0] + '"]').is(':blank');
    }, "Please fill out only one of these fields");

    $('#myform').validate({
        rules: {
            foo: {
                onlyOne: ["bar"],
                number: true
            },
            bar: {
                onlyOne: ["foo"],
                number: true
            }
        }
    });

});

Then use a blur keyup handler to ensure the validation messages update themselves on all fields. Again, since I have no idea if you have other fields on this form, adjust these selectors to only target what's relevant and needed.

$('input').on('blur keyup', function() {
    $('#myform').valid();  // force validation on entire form
});

Proof-of-Concept DEMO: http://jsfiddle.net/e01d5sw7/


EDIT:

As per OP's comments, while both fields should not be filled out at the same time, one field or the other is required...

$.validator.addMethod('onlyOne', function(value, element, param) {
    return ($(element).is(':filled') && $('[name="' + param[0] + '"]').is(':blank')) ||
    (($('[name="' + param[0] + '"]').is(':filled')) && $(element).is(':blank'));
}, "Please fill out only one of these fields");

DEMO #2: http://jsfiddle.net/Lnxxgs92/