ASP.NET MVC 5 Jquery Validate

  1. ClientValidationEnabled

    在asp.net mvc 5中ClientValidationEnabled默認爲TRUE,因此也不須要刻意去設置javascript

  2. 應用ValidationAttribute

    這裏使用內置的RequiredAttribute來演示html

    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總覽java

<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的設置,若是不知足條件則顯示錯誤提示jquery

相關文章
相關標籤/搜索