简体   繁体   中英

Validate dependent select options with jQuery Validation plugin

INTRODUCTION

I am using jQuery Validation plugin to validate form before submitting it to the server. For simple cases it works great. Yet i find official documentation lacking some more advanced examples.

IMAGINE

Imagine there is internet shop with 3 locations (Berlin, Paris and Rome). Yet delivery with courier service is available only in one location (Berlin). Note that: orders can be sent by post to all three locations.

I would like to make sure that validation displays an error if user chooses courier service in conjunction with Rome or Paris.

PROBLEM

I am trying to validate two selects that depend on each others option values. Though, i can not figure out how to make it happen.

CODE

JsFiddle of my code

html

<form id="myForm" name="myForm">
  <p><b>Order delivery</b></p>
  <p>
    City<br />
    <select name="city" id="city">
      <option selected value="">-- Please choose destination --</option>
      <option value="1">Berlin</option>
      <option value="2">Paris</option>
      <option value="3">Rome</option>
    </select>
  </p>
  <p>
    Delivery method<br />
    <select name="delivery" id="delivery">
      <option selected value="">-- Please choose delivery method --</option>
      <option value="1">By post</option>
      <option value="2">By courier</option>
    </select>
  </p>
  <input type="submit" />
</form>

javascript

$( document ).ready( function () {
    jQuery.validator.addMethod("valueIsDeliveryPost", function(elementValue, element, param) {
        if (elementValue == 1) {
            return true;
        } else {
            return false;
        }
    }, "Value must equal param.");

    jQuery.validator.addMethod("valueIsDeliveryCourier", function(elementValue, element, param) {
        if (elementValue == 2) {
            return true;
        } else {
            return false;
        }
    }, "Value must equal param.");

    jQuery.validator.addMethod("valueIsEqualTo", function(elementValue, element, param) {
        return elementValue == param;
    }, "Value must equal param.");

    jQuery.validator.addMethod("valueIsNotEqualTo", function(elementValue, element, param) {
        return elementValue != param;
    }, "Value must not equal param.");

    $("#myForm").validate({
        debug: true,
        rules: {
            city: {
                required: true,
                valueIsNotEqualTo: "default"
            },
            delivery: {
                required: true,
                valueIsNotEqualTo: "default",
                valueIsDeliveryPost: {
                    param: 1, // if delivery by post is selected
                    depends: function(element) {
                        var cityVal = $("#city").val();
                        if ((cityVal != "") && (cityVal == 1)) { // if Berlin
                            return false;
                        } else if ((cityVal != "") && (cityVal == 2)) { // if Paris
                            return false;
                        } else if ((cityVal != "") && (cityVal == 3)) { // if Rome
                            return false;
                        }/* else {
                            return true;
                        }*/
                    }
                },
                valueIsDeliveryCourier: {
                    param: 2, // if delivery by courier is selected
                    depends: function(element) {
                        var cityVal = $("#city").val();
                        if ((cityVal != "") && (cityVal == 1)) { // if Berlin
                            return true;
                        } else if ((cityVal != "") && (cityVal == 2)) { // if Paris
                            return false;
                        } else if ((cityVal != "") && (cityVal == 3)) { // if Rome
                            return false;
                        }/* else {
                            return true;
                        }*/
                    }
                }
            },
        },
        messages: {
            city: {
                required: "Please select your city!",
                valueIsNotEqualTo: "Please select your city!"
            },
            delivery: {
                required: "Please select delivery method!",
                valueIsNotEqualTo: "Please select delivery method!",
                valueIsDeliveryPost: "Delivery by post is possible for all cities!",
                valueIsDeliveryCourier: "Courier delivery is possible only in Berlin!"
            },
            errorElement: "em",
            errorPlacement: function (error, element) {
                return false;
            },
            invalidHandler: function(form, validator) {
                var errors = validator.numberOfInvalids();
                if (errors) {
                    // Only show first invalid rule message
                    alert(validator.errorList[0].message);
                    // Set focus
                    validator.errorList[0].element.focus();
                }
            },
            highlight: function (element, errorClass, validClass) {
                $(element).addClass("is-invalid").removeClass( "is-valid" );
            },
            unhighlight: function (element, errorClass, validClass) {
                $(element).addClass("is-valid").removeClass( "is-invalid" );
            },
            submitHandler: function(form) {
                alert('valid form');
            }
        }
    });
});

FINALLY

I think that cause of the problem might be wrong logic in dependent select validation code.

What am i doing wong?

Please share your expertize and ideas.

Your logic seems to work fine.

If you click the "tidy" button in your jsFiddle , you can see that you incorrectly nested the errorElement , errorPlacement , invalidHandler , submitHandler , highlight , and unhighlight options inside of messages .

These options are supposed to be siblings of messages and rules .

$("#myForm").validate({
    rules: {
        ....
    },
    messages: {
        ....
    },
    errorElement: "em",
    errorPlacement: function (error, element) {
        ....
    },
    invalidHandler: function(form, validator) {
        ....
    },
    highlight: function (element, errorClass, validClass) {
        ....
    },
    unhighlight: function (element, errorClass, validClass) {
        ....
    },
    submitHandler: function(form) {
        ....
    }
});

DEMO: jsfiddle.net/pey29j4n/2/

NOTE : I totally agree with Daniel. It makes no sense to present the user with invalid options in the first place, and it would be far easier to dynamically add/remove the option from the select .

Here is a very crude proof-of-concept:

$('#city').on('change', function() {
    if ($(this).val() == '1') {
        $('#delivery option[value="1"]').remove();
    }
});

Or you could disable the option by ghosting it out :

$('#city').on('change', function() {
    var option = $('#delivery option[value="1"]');
    if ($(this).val() == '1') {
        option.attr('disabled', true);
    } else {
        option.attr('disabled', false);
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM