[英]How to give mandatory field validation for select2 fields in asp.net mvc 4
我在我的MVC 4.0項目中使用select2插件作為選擇列表。
但是當我們使用select2時,MVC的默認驗證失敗了。 有時候選擇列表會出現錯誤消息,但是當我們從選擇列表中選擇值時,它不會自動清除。
請給我關於任何其他客戶端驗證的建議
以下是我的項目代碼。
.cshtml
<div class="editor-field">
<select id="cityid">
<option></option>
</select>
@Html.ValidationMessageFor(model => model.CityID)
<script type="text/javascript">
$("#cityid").select2({
placeholder: "Select City",
width: "200px"
});
</script>
</div>
型號代碼:
[Required(ErrorMessage="Please select city")]
public int CityID { get; set; }
請幫我解決這個問題
(function() {
var $select = $('select').select2({
placeholder: 'Choose',
allowClear: true
});
/*
* When you change the value the select via select2, it triggers
* a 'change' event, but the jquery validation plugin
* only re-validates on 'blur'
*/
$select.on('change', function() {
$(this).trigger('blur');
});
$('#myForm').validate({
ignore: 'input[type=hidden], .select2-input, .select2-focusser'
});
$select.rules('add', 'required');
}());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.