return PartialView("_ViewSchoolPartial", viewModel);
<script type="text/javascript">
$('#form1').validate({
rules: {
Name: {
required: true,
minlength: 2,
maxlength: 5
},
JobTitle: {
required: true,
minlength: 2,
maxlength: 5
},
Phone: {
required: true,
minlength: 5,
maxlength: 20
},
Email: {
required: true,
email: true,
minlength: 5,
maxlength: 40
}
},
messages: {
Name: {
required: '*必填欄位',
minlength: '*最短字數為2個字元!',
maxlength: '*最長字數為5個字元!'
},
JobTitle: {
required: '*必填欄位',
minlength: '*最短字數為2個字元!',
maxlength: '*最長字數為5個字元!'
},
Phone: {
required: '*必填欄位',
minlength: '*最短字數為5個字元!',
maxlength: '*最長字數為20個字元!'
},
Email: "*電子郵件格式不正確"
},
//以下css可換成自己的
highlight: function (element) {
$(element).closest('input').addClass('input-validation-error');
},
unhighlight: function (element) {
$(element).closest('input').removeClass('input-validation-error');
},
errorElement: 'span',
errorClass: 'field-validation-error',
errorPlacement: function (error, element) {
if (element.parent('input').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
</script>
後來發現有個外國人寫了一個Plugin解決動態載入驗證失效的問題,上面看看就好。
$("#divPanel").html(res);
在動態載入的下方加入以下即可
$.validator.unobtrusive.parseDynamicContent(
'#formID'
);
然後我畫面一直出現parseDynamicContent undefined,我明明頁面上都引入的js,
後來把這4隻js移到最下方終於可以了
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.dynamic.js"></script>
請參考以下網站
https://xhalent.wordpress.com/2011/01/24/applying-unobtrusive-validation-to-dynamic-content/
最新解決方案 20190430
$("#divPanel").html(res);
//動態載入後請使用下列方式
$.validator.unobtrusive.parse("#form2");
使用jQuery Validation Plugin v1.17.0