ASP.NET MVC 5 Jquery Validate

  1. ClientValidationEnabled

    在asp.net mvc 5中ClientValidationEnabled默认为TRUE,所以也不需要刻意去设置

  2. 应用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; }
    }
  3. 引用相关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>
  4. 在View中显示错误消息
       @Html.ValidationSummary()
    @Html.ValidationMessageFor(o => o.BookID)
  5. 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的设置,如果不满足条件则显示错误提示

ASP.NET MVC 5 Jquery Validate

上一篇:django(django学习) 两张表创建 插入数据


下一篇:hdu 3549 Flow Problem (Dinic)