我正在使用jQuery UI MultiSelect Widget我想要进行多项选择,因为它们应该选择至少一个值。我知道多选是隐藏的,这就是为什么它不仅仅是验证,而是让问题得到验证忽略隐藏并验证控件。这是我的观看代码。
<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;
}
}
答案 0 :(得分: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);