Validate triple input box phone number field with jquery validate

- 1 answer

Ad

I am trying to make phone number required if some logic holds true. When logic does hold true i see first two phone number fields say phone number is required even though i have entered something in them, only the third one doesn't show error. The error only goes away when i manually click on first two fields.

I also tried calling valid() method on first two phone fields inside phoneValidation method but it was causing infinite loop understandably. I suppose i can make this work by adding different validator methods for all three phone boxes but is there an elegant way to do this?

    <div class="form-inline" style="margin-top: 5px;">
        <input type="text" name="phone1" id="phone1" class="form-control" maxlength="3" size="3" />&nbsp;-&nbsp;
        <input type="text" name="phone2" id="phone2" class="form-control" maxlength="3" size="3" />&nbsp;-&nbsp;
        <input type="text" name="phone3" id="phone3" class="form-control" maxlength="4" size="4" />
    </div>

JS

     $("#thisForm").validate({
        rules: {
            "phone1" : { maxlength: 3, minlength: 3, digits: true, phoneValidation: true},
            "phone2" : { maxlength: 3, minlength: 3, digits: true, phoneValidation: true},
            "phone3" : { maxlength: 4, minlength: 4, digits: true, phoneValidation: true}
        }
     });


    $.validator.addMethod("phoneValidation", function(value, element) {
        // some logic
        if ($("#someField").is(":checked"))
            return true;

        if (!$("#phone1").val() || !$("#phone2").val() || !$("#phone3").val()) {
            return false;
        }

        return true;
    }, "phone is required.");
Ad

Answer

Ad

I kept the original solution. The validation errors on the first two fields goes away when you click on them or submit form. Not ideal but not a show stopper!

Ad
source: stackoverflow.com
Ad