- ClientValidationEnabled
在asp.net mvc 5中ClientValidationEnabled默认为TRUE,所以也不需要刻意去设置
- 应用ValidationAttribute
这里使用内置的RequiredAttribute来演示
public class Book
{
[Required(ErrorMessage = "BookID Is Required")]
public string BookID { get; set; } public string Title { get; set; } public string Date { get; set; }
} - 引用相关JQuery
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script> - 在View中显示错误消息
@Html.ValidationSummary()
@Html.ValidationMessageFor(o => o.BookID) - DOMReady中设置validate
<script type="text/javascript">
$(function () {
$("form").validate();
});
</script>
客户端view总览
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>View</title>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script type="text/javascript">
$(function () {
$("form").validate();
});
</script>
</head>
<body>
<form action="/Home/ShowBook" method="POST">
@Html.ValidationSummary()
@Html.ValidationMessageFor(o => o.BookID) BookID @Html.EditorFor(o => o.BookID) Title
@Html.EditorFor(o => o.Title,new { @value= "WCF解密" })
Day <input id="Day" name="Day" value="12" type="text" />
Month <input id="Month" name="Month" value="12" type="text" />
Year <input id="Year" name="Year" value="2016" type="text" /> <input id="Submit" type="Submit" value="Submit" />
</form>
</body>
</html>
在这个例子中当你提交表单的时候,会验证客户端的数据是否符合validationAttribute的设置,如果不满足条件则显示错误提示