ASP.NET MVC 常用內建驗證特性 簡介

來源:互聯網
上載者:User

標籤:表達   sharp   email   ror   rem   method   class   duration   使用者名稱   

 

0.[DisplayName("名字")]

0.[DisplayName("名字")]

 

1.[Required] : 必須輸入

[Required(ErrorMessage = "請輸入使用者名稱")]  

 

2.[StringLength] : 限制字串長度 

[StringLength(10, ErrorMessage = "長度不能超過10個字元")]  

 

3.[Range] : 限制取值範圍  

1 [Range(0, 120, ErrorMessage = "年齡範圍在0到120歲之間")]  

  

4.[RegularExpression] : 必須符合某個Regex(1)直接使用RegularExpression來寫運算式:  

1 [RegularExpression(@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "請輸入Email格式")]  2 public String RegualarExpressionField { get; set; }  

 

 

(2)自訂特性: 

1 public class EmailAttribute : RegularExpressionAttribute  2     {  3         public EmailAttribute()  4             :base(@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$")  5         {  6         }  7     }  

 



5.Compare 判等比較 

public string Email { get; set; }    [Compare("Email", ErrorMessage = "郵箱要相同")]  public string TEmail { get; set; }  

 

6.Remote : Ajax遠程驗證,傳回值是bool類型 true表示驗證通過

//   Action方法 控制器類    請求方式  [Remote("User", "Validate", HttpMethod = "post", ErrorMessage = "使用者名稱已經存在")]  public string UserName { get; set; }  //....  public ActionResult User()  {  //..    if(true)    {      return Json(true,JsonRequestBehavior.AllowGet);    }    else      return Json(false,JsonRequestBehavior.AllowGet);    }  

 

 

7.OutputCache 頁面緩衝 

[OutputCache(Duration=20)]//設定頁面絕對緩衝  緩衝時間為 20秒  public ActionResult Index()  {       //詳細代碼  }  

 

8.隱藏欄位

 [HiddenInput(DisplayValue=false)]public string Name { get; set; }

 

ASP.NET MVC 常用內建驗證特性 簡介

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.