0

我正在使用 jQuery UI MultiSelect 小部件我想让多选成为必需,因为他们应该选择至少一个值。我知道多选是隐藏的,这就是为什么它不只是验证,而是让验证忽略隐藏并验证控件的问题。这是我的视图代码。

<div class="editor-field">
  @Html.ListBoxFor(model => model.SelectedItems,new MultiSelectList(Model.AvailableDistributionEntities, "Value", "Text", Model.SelectedItems),new {@class = "multiselect ", id="mySelect", name="mySelect", style ="width:50%;"})
  @Html.ValidationMessageFor(x => x.SelectedItems)
</div>


<script type="text/javascript">
  $.validator.addMethod("needsSelection", function (value, element) {
    return $(element).multiselect("getChecked").length > 0;
  });

  $.validator.messages.needsSelection = 'Please select at least one email distribution list.';

  jQuery.validator.unobtrusive.adapters.add("needsSelection", [], function (options) {
    options.rules["needsSelection"] = true;
    options.messages["needsSelection"] = options.message;
  });  
</script>

这是 bootbox.dialog 内的部分视图,因此在发送回调时我正在进行验证。不知道为什么它不验证该控件。

label: "Send",
className: "btn-primary btn-xs",
callback: function () {
  var $form = $('#form');
  //Validating the form using unobtrusive validation.
  $.validator.unobtrusive.parse($form);

  $("#form").validate({
    // options
    rules: {
      "needsSelection": "required",
    },
    ignore: ':hidden:not(.multiselect)'
  });

  if ($("#form").valid()) {
    $.ajax({
      cache: false,
      url: "/Email/Distribute",
      type: 'POST',
      //Serializing the form data to pass to the edit action.
      data: $("#form").serialize(),
      success: function (res) {
        if (res.success) {
          //Refreshing the event schedule edit screen by navigating to it.
          navigateTo(res.url);
        } else {
          alert("Error occurred while saving.");
        }
      }
    });
  } else {
    return false;
  }
}
4

1 回答 1

0

我找到了将忽略添加到不显眼的验证以使其正常工作所需的解决方案。这是我添加的行

$.validator.setDefaults({ ignore: [] });
var $form = $('#form');
//Sets the unobtrusive validation to ignore the hidden and still perform the validation.
$.validator.setDefaults({ ignore: [] });

//Validating the form using unobtrusive validation.
$.validator.unobtrusive.parse($form);
于 2014-03-07T14:13:14.213 回答