Jquery - 在对话框中为动态生成的下拉列表添加自定义验证规则

时间:2014-10-16 13:17:44

标签: jquery jquery-validate

我在jquery对话框中创建了一些动态下拉列表,我想用规则验证它们:只应选择其中一个下拉列表。

我是Jquery的新手,在google搜索时发现了这样就可以通过Jquery validate plugin实现。

所以我下载了Jquery validate插件并将其加载到页面上,但我无法更正验证代码。

到目前为止,我已经创建了对话框&填充了动态控件,但不确定如何添加动态规则。

对此有任何建议会有所帮助。

由于

填充动态控件:

if (conflictOccured) {
            for (a = 0; a < selectedOoOptions.length; a++) {                                         
                    if (selectedOoOptions[a].OptionId == selectedOptionId) {
                        var item = populateListItem(selectedOptionId, selectedOoOptions[a].Description, paidById, "OoPaidByOption2");                                                      
                        break;
                    }                  
            }
            $("#OptionsUI").empty();
            $.each(OutputArray, function (obj, i) {
                $('#OptionsUI').append(i);
            });

            OutputArray = [];
            initialiseDialog();
            $("#optionsDialog").dialog("open");
            return false;
        }


function populateListItem(optionId, description, paidById, optionName) {
            return '<li>' +
                        '<span>' +
                            '<input type="hidden" id="OptionsId" value="' + optionId + '" /> </span>' +
                            '<span>' + description + '</span>' +
                        '</span><select class="select" id="OptionPaidbyList" name="'+ optionName +'">' +
                            '<option value="0">Select</option>' +
                            '<option value="1">On Rent</option>' +
                            '<option value="2">Paid</option>' +
                            '</select>' +
                    '</li>';
        }

Dialog DIV

 <div id="optionsDialog" title="Please select">
    <form id="OptionsDialogForm">
        <div id="OoOptions_div">
            <p id="RuleTitle"></p>    
            <ul id="ooOptionsUI">           
            </ul>
        </div>
        <div id="ValidationError_div"></div>
    </form>       
</div>

初始化对话

 function initialiseDialog() {        
        var $this = this;
        $("#optionsDialog").dialog({
            autoOpen: false,
            modal: true,
            width: 650,
            dialogClass: "no-close",
            open: function (event, ui) {
                $('#OptionsDialogForm').validate({  // initialize the plugin
                    // your other rules or options,                
                    errorPlacement: function (error, element) {                          
                        error.appendTo($('#ValidationError_div'))

                    }
                });

                $('[name^="OoPaidByOption"]').each(function () { // all names starting with 'OoPaidByOption'
                    $(this).rules('add', {        // attach same rules to each of these fields
                        required: {
                            depends: function (element) {
                                return $(this).closest('option:selected').val() != 0
                            }
                        },
                        messages: {
                            required: "Please select a option"
                        }
                    });
                    alert("rules applied");
                });
            },
            buttons: {
                OK: function (event, ui) {                       
                    if ($("#OptionsDialogForm").valid()) {
                        resolveConflict()
                    }
                },
                Cancel: function (event, ui) {
                    closeDialog();
                }
            }
        });
    }

验证规则:(此代码现已删除)

 $('#ooOptionsUI > li').each(function(){
            $(this).rules("add", {
                option1: {
                    required: {
                        depends: function (element) {
                            return $('#OoPaidByOption1 option:selected').val() != 0
                        }
                    }
                },
                option2: {
                    required: {
                        depends: function (element) {
                            return $('#OoPaidByOption2 option:selected').val() != 0;
                        }
                    }
                },
                messages: {
                    option1: "Please select only one option",
                    option2: "Please select only one option"
                },
                errorPlacement: function (error, element) {
                    error.appendTo($('#OoValidationError_div'))
                }
            });
        });

HTML制作:

<div class="ui-dialog ui-widget ui-widget-content ui-corner-all no-close ui-draggable ui-resizable ui-dialog-buttons" tabindex="-1" style="outline: 0px; z-index: 1002; position: absolute; height: auto; width: 650px; top: 348.5px; left: 302px; display: block;" role="dialog" aria-labelledby="ui-id-1">
<div class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix"><span id="ui-id-1" class="ui-dialog-title">Please select</span><a href="#" class="ui-dialog-titlebar-close ui-corner-all" role="button"><span class="ui-icon ui-icon-closethick">close</span></a></div>
<div id="optionsDialog" class="ui-dialog-content ui-widget-content" scrolltop="0" scrollleft="0" style="width: auto; min-height: 1px; height: auto;">
    <form id="OptionsDialogForm" novalidate="novalidate">
        <div id="OoOptions_div">
            <p id="RuleTitle"></p>
            <ul id="ooOptionsUI">
                <li><span>
                    <input type="hidden" id="OptionsId" value="1"></span><span>17" alloy wheels</span>
                    <select class="select valid" id="OptionPaidbyList" name="OoPaidByOption1" aria-required="true" aria-invalid="false">
                        <option value="0">Select</option>
                        <option value="1">Rental</option>
                        <option value="2">Paid</option>
                    </select></li>
                <li><span>
                    <input type="hidden" id="Hidden1" value="2">
                </span><span>18" alloy wheels </span>
                    <select class="select" id="Select1" name="OoPaidByOption2" aria-required="true">
                        <option value="0">Select</option>
                        <option value="1"> Rental</option>
                        <option value="2">Paid</option>
                    </select></li>
            </ul>
        </div>
        <div id="ValidationError_div"></div>
    </form>
</div>   
<div class="ui-dialog-buttonpane ui-widget-content ui-helper-clearfix">
    <div class="ui-dialog-buttonset">
        <button type="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false"><span class="ui-button-text">OK</span></button>
        <button type="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false"><span class="ui-button-text">Cancel</span></button>
    </div>
</div>

1 个答案:

答案 0 :(得分:0)

首先让我解释为什么以下是完全错误的......

 $('#ooOptionsUI > li').each(function(){
     $(this).rules("add", {
        option1: {
            ....
        },
        option2: {
            ....
        },
        messages: {
            ....
        },
        errorPlacement: function (error, element) {
            ....
        }
    });
});
  1. 您的选择器$('#ooOptionsUI > li')正在定位li元素。 .rules()方法只能附加到inputtextareaselect元素,而不是li元素。

  2. 您的.rules()方法包含字段名称列表option1option2。由于.rules()方法已附加到字段,因此它只能包含与该字段和messages选项相关的规则列表;没有其他的。 (将.rules()方法附加到字段然后在其中放入更多字段没有任何意义。)

  3. 您的.rules()方法包含errorPlacement选项。 .rules()方法只能包含规则列表和messages选项;没有其他的。 errorPlacement选项只能 放在.validate().setDefaults()方法内。


  4. 由于您有一个专为一个字段编写的depends选项,因此您必须分别对每个字段使用.rules()方法。

    看起来应该更像......

    $('#yourForm').validate({  // initialize the plugin
        // your other rules or options,
        errorPlacement: function (error, element) {
            error.appendTo($('#OoValidationError_div'))
        }
    });
    
    $('[name="myField_1"]').rules('add', {  // attach rules to field 1
        required: {
            depends: function (element) {
                return $('#OoPaidByOption1 option:selected').val() != 0
            }
        },
        messages: {
            required: "Please select only one option"
        }
    });
    
    $('[name="myField_2"]').rules('add', {  // attach rules to field 2
        required: {
            depends: function (element) {
                return $('#OoPaidByOption2 option:selected').val() != 0
            }
        },
        messages: {
            required: "Please select only one option"
        }
    });
    

    我无法看到您呈现的HTML,但可能有一种方法可以将所有内容组合在一起。只有当你有更通用的方式编写depends函数时才会这样做。

    这只是一个通用的建议......

    $('[name^="myField"]').each(function() { // all names starting with 'myField'
        $(this).rules('add', {        // attach same rules to each of these fields
            required: {
                depends: function (element) {
                    return $(this).closest('option:selected').val() != 0
                }
            },
            messages: {
                required: "Please select only one option"
            }
        });
    });
    

    好的,现在我明白为什么你认为你需要depends选项。这不是depends选项的工作方式,在这种情况下,它不是必需的。

    更改您的HTML,以便select看起来像这样。请注意,首先option包含value=""

    <select class="select valid" id="OptionPaidbyList" name="OoPaidByOption1" aria-required="true" aria-invalid="false">
        <option value="">Select</option>
        <option value="1">Rental</option>
        <option value="2">Paid</option>
    </select>
    

    然后你的.rules()方法可以就是这个......

    $('[name^="myField"]').each(function() { // all names starting with 'myField'
        $(this).rules('add', {        // attach same rules to each of these fields
            required: true,
            messages: {
                required: "Please select only one option"
            }
        });
    });
    

    DEMO:http://jsfiddle.net/mL6x8enc/