簡體   English   中英

使用jQuery Validation插件驗證依賴選擇選項

[英]Validate dependent select options with jQuery Validation plugin

介紹

我正在使用jQuery Validation插件來驗證表單,然后再將其提交給服務器。 對於簡單的情況,它很好用。 但是我發現官方文檔缺少一些更高級的示例。

想像

想象一下,有3個位置(柏林,巴黎和羅馬)的互聯網商店。 然而,僅在一個位置(柏林)提供快遞服務送貨。 請注意:訂單可以通過郵寄發送到所有三個位置。

如果用戶與羅馬或巴黎一起選擇快遞服務,我想確保驗證顯示錯誤。

問題

我試圖驗證兩個選擇,這些選擇取決於彼此的選項值。 雖然,我不知道如何實現它。

我的代碼的JsFiddle

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');
            }
        }
    });
});

最后

我認為問題的原因可能是從屬選擇驗證代碼中的邏輯錯誤。

我在做什么呢?

請分享您的專業知識和想法。

您的邏輯似乎很好。

如果您單擊“整理”按鈕, 您的jsfiddle ,你可以看到你錯誤地嵌套在errorElementerrorPlacementinvalidHandlersubmitHandlerhighlightunhighlight的內部選項messages

這些選項應該是messagesrules同級。

$("#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) {
        ....
    }
});

演示: jsfiddle.net/pey29j4n/2/

注意 :我完全同意丹尼爾。 首先向用戶顯示無效選項是沒有意義的,並且從select動態地添加/刪除option會容易得多。

這是一個非常粗糙的概念證明:

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

或者,您可以通過將其重影禁用該option

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM