【问题标题】:How to perform conditional client side validation by jquery validate plugin如何通过 jquery validate 插件执行条件客户端验证
【发布时间】:2016-03-30 20:21:54
【问题描述】:

我在这里给出我的 html。我有一个下拉菜单,其中显示很少的产品信息并通过复选框显示爱好。我想如果用户选择产品 iPod 然后验证不会触发爱好复选框,否则会触发。如何通过 jquery validate 插件添加 jquery 规则来执行这种条件验证。

<form name="TestVal" method="post" action="/" novalidate="novalidate">
    <div class="form-horizontal">
        <h4>DateValTest</h4>
        <hr>

        <div class="form-group">
            <label style="padding-top: 0px;" for="Products" class="control-label col-md-2">Products</label>
            <div class="col-md-10">
                <select name="SelectedProductId" id="SelectedProductId" data-val-required="Select any Product" data-val-number="The field SelectedProductId must be a number." data-val="true">
                    <option value="">-- Select Product--</option>
                    <option value="1">IPhone</option>
                    <option value="2">MacBook Pro</option>
                    <option value="3">iPod</option>
                </select>
                <span data-valmsg-replace="true" data-valmsg-for="SelectedProductId" class="field-validation-valid text-danger"></span>
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10 input-validation-error">
                <b>Hobbies</b><br>
                <input type="checkbox" value="true" name="Hobbies[0].IsSelected" id="Hobbies" data-val-required="The IsSelected field is required." data-val="true" class="hobbycls"><input type="hidden" value="false" name="Hobbies[0].IsSelected">
                &nbsp; 
                <label for="Hobbies_0__IsSelected">Reading</label>
                &nbsp;
                <input type="hidden" value="Reading" name="Hobbies[0].Name" id="Hobbies_0__Name"><input type="checkbox" value="true" name="Hobbies[1].IsSelected" id="Hobbies" data-val-required="The IsSelected field is required." data-val="true" class="hobbycls"><input type="hidden" value="false" name="Hobbies[1].IsSelected">
                &nbsp; 
                <label for="Hobbies_1__IsSelected">Sports</label>
                &nbsp;
                <input type="hidden" value="Sports" name="Hobbies[1].Name" id="Hobbies_1__Name"><input type="checkbox" value="true" name="Hobbies[2].IsSelected" id="Hobbies" data-val-required="The IsSelected field is required." data-val="true" class="hobbycls"><input type="hidden" value="false" name="Hobbies[2].IsSelected">
                &nbsp; 
                <label for="Hobbies_2__IsSelected">Movies</label>
                &nbsp;
                <input type="hidden" value="Movies" name="Hobbies[2].Name" id="Hobbies_2__Name">
            </div>

        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" class="btn btn-default" value="Submit">
            </div>
        </div>
    </div>
</form>

现在我正在通过这种方式进行客户端验证

<script type="text/javascript">
    var declarationsError = $('#Hobbies-error');
    $('form').submit(function () {
        if ($("#SelectedProductId option:selected").text() != 'iPod') {
            if ($(".hobbycls:checkbox:checked").length <= 0) {
                declarationsError.empty();
                declarationsError.append("<span>Select Any Hobbie's checkbox</span>");
                declarationsError.show();
                return false;
            } else {
                declarationsError.empty();
                declarationsError.hide();
            }
        }

        declarationsError.hide();
        return true;
    });

    $('.hobbycls').change(function () {
        if ($(this).is(':checked')) {
            declarationsError.empty();
            declarationsError.hide(); // hide error message
        }
    });
</script>

上面的脚本工作正常,但我想使用 jquery validate 插件添加规则来做同样的事情。

所以请指导我需要编写什么 jquery 验证代码来执行相同的操作。向我展示如何通过添加 jquery 规则来进行这种条件验证。谢谢

【问题讨论】:

    标签: jquery jquery-validate


    【解决方案1】:

    您在生成的 HTML 中有一些错误:

    1. 不同元素的相同 ID(即:爱好)
    2. 标签未链接到任何元素:即:label for="Products"

    您可以使用 jQuery 验证器添加新规则,以准确重复您在两个 jQuery 函数中所做的操作:

    1. $('form').submit(function () {
    2. $('.hobbycls').change(function () {

    你忘了给 Hobbies-error 元素,所以我用了一个 div。

    下面是sn-p:

    var validator;
    
    // a new rule is required to test if iPod is selected and checkboxes are...
    $.validator.addMethod('checkboxMaxIfiPodNotSelected', function (value, elem, param) {
      var selectedOptionVal = $(param.selEleiSiPod).val().trim();
      var selectedOptionText = $(param.selEleiSiPod).text().trim();
      if (selectedOptionText != 'iPod') {
        if (selectedOptionVal.length > 0) {
          if ($(':checkbox.' + elem.classList[0] + ":checked").length <= param.max) {
            $('#Hobbies-error').empty().append("<span>Select Any Hobbie's checkbox</span>").show();
            return false;
          }
        } else {
          $('#Hobbies-error').empty().append("<span>Select a Product</span>").show();
          return false;
        }
      }
      $('#Hobbies-error').empty().hide();
      return true;
    });
    
    $(function () {
      // build the dynamic rules....
      var myRules = {};
      var myMessages = {};
      $(':checkbox.hobbycls').each(function (index, element) {
        myRules[element.name] = {
          checkboxMaxIfiPodNotSelected: {
            max: 0,
            selEleiSiPod: '#SelectedProductId option:selected'
          }
        };
        myMessages[element.name] = {
          checkboxMaxIfiPodNotSelected: function(params, element) {
            // it's not usefull to return a true error message because I used a div
            // but this is up to you how to manage and place the errors
            return '';
          }
        };
      });
    
      // use the rules and messages with validator...
      validator = $('form').validate({
        rules: myRules,
        messages: myMessages,
        submitHandler: function (form) { // for demo
          alert('valid form submitted'); // for demo
          return false; // for demo
        }
      });
    });
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>
    
    
    <form name="TestVal" method="post" action="/" novalidate="novalidate">
        <div class="form-horizontal">
            <h4>DateValTest</h4>
            <hr>
    
            <div class="form-group">
                <label style="padding-top: 0px;" for="SelectedProductId" class="control-label col-md-2">Products</label>
    
                <div class="col-md-10">
                    <select name="SelectedProductId" id="SelectedProductId"
                            data-val-required="Select any Product"
                            data-val-number="The field SelectedProductId must be a number." data-val="true">
                        <option value="">-- Select Product--</option>
                        <option value="1">IPhone</option>
                        <option value="2">MacBook Pro</option>
                        <option value="3">iPod</option>
                    </select>
                    <span data-valmsg-replace="true" data-valmsg-for="SelectedProductId"
                          class="field-validation-valid text-danger"></span>
                </div>
            </div>
    
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10 input-validation-error">
                    <b>Hobbies</b><br>
                    <input type="checkbox" value="true" name="Hobbies[0].IsSelected" id="Hobbies"
                           data-val-required="The IsSelected field is required." data-val="true" class="hobbycls"><input
                        type="hidden" value="false" name="Hobbies[0].IsSelected">
                    &nbsp;
                    <label for="Hobbies_0__Name">Reading</label>
                    &nbsp;
                    <input type="hidden" value="Reading" name="Hobbies[0].Name" id="Hobbies_0__Name">
                    <input type="checkbox" value="true" name="Hobbies[1].IsSelected" id="Hobbies1"
                           data-val-required="The IsSelected field is required."
                           data-val="true" class="hobbycls">
                    <input type="hidden" value="false" name="Hobbies[1].IsSelected">
                    &nbsp;
                    <label for="Hobbies_1__Name">Sports</label>
                    &nbsp;
                    <input type="hidden" value="Sports" name="Hobbies[1].Name" id="Hobbies_1__Name">
                    <input type="checkbox" value="true" name="Hobbies[2].IsSelected" id="Hobbies2"
                           data-val-required="The IsSelected field is required."
                           data-val="true" class="hobbycls">
                    <input type="hidden" value="false" name="Hobbies[2].IsSelected">
                    &nbsp;
                    <label for="Hobbies_2__Name">Movies</label>
                    &nbsp;
                    <input type="hidden" value="Movies" name="Hobbies[2].Name" id="Hobbies_2__Name">
                </div>
            </div>
    
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" class="btn btn-default" value="Submit">
                </div>
            </div>
        </div>
        <div id="Hobbies-error" class="help-block with-errors"></div>
    </form>

    【讨论】:

    • 当我从产品下拉列表中选择除 ipod 以外的任何产品时,用户必须选择一个爱好复选框,但我测试您的代码并发现没有显示错误消息。你能提供你的修正代码的js小提琴版本吗?这个时间码不起作用。
    • 能不能看几篇没有答案的帖子。这是3个网址。请检查网址并尽可能提供。 stackoverflow.com/questions/36306822/…stackoverflow.com/questions/36306563/…stackoverflow.com/questions/36287583/…
    • @Mou 你好,我刚刚看完你的下一个问题。我很抱歉,但此刻我正在学习 js、angularjs、reactjs、bootstrap ......关于 MVA 和书籍。我暂时停在服务器端。这个周末,我参加了我最后一次针对高级用户的 js MVA 课程(非常有趣)。抱歉,我不能也没有时间解决您的问题。我希望你原谅我。我对客户端太感兴趣了。再见。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-13
    • 2014-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多