MVC - 13.驗證

來源:互聯網
上載者:User

標籤:style   color   java   使用   io   strong   for   ar   

1.MVC驗證

1.1.驗證方式

引入命名空間

using System.ComponentModel.DataAnnotations;

定義驗證規則:

Model屬性添加內建驗證特性,介紹用的最多的其中的四個:

[Required], [StringLength], [Range], 和 [RegularExpression]

[StringLength(4,ErrorMessage="您使用的名稱太長了~")]        public string Name { get; set; }

產生的Html代碼:

<input type="text" value="" name="Name" id="Name" data-val-length-max="4" data-val-length="您使用的名稱太長了~" data-val="true" class="text-box single-line">

 

用戶端驗證:

1.引入JS指令碼支援

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>

<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

2.添加語句

@{Html.EnableClientValidation(true);}(MVC3中預設開啟)

服務端驗證:

控制器中使用:ModelState.IsValid 判斷是否通過驗證

 

*定義自己的定製驗證特性,然後應用它們。你可以通過繼承自System.ComponentModel.DataAnnotations命名空間中 的ValidationAttribute基類,定義完全定製的特性。

public class EmailAttribute : RegularExpressionAttribute

{

public EmailAttribute()

:base(@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$")

{

}

}

1.2.顯示錯誤訊息:

在儲存格後面顯示:@Html.ValidationMessageFor(s=>s.Name)

集中在一個地方顯示:@Html.ValidationSummary()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.