using System;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
public partial class Room
{
[Required]
public string RoomID { get; set; }
[Required]
[StringLength(6)]
public string Roomtype { get; set; }
public int Rate { get; set; }
}
在 Room 這個 Class中, Roomtype 這個變數前面有兩個 Annotations, [Required] 和 [StringLength(6)]. [Required] 表示這是一個必要欄位, [StringLength(N)] 則限制最大長度, 這個長度是傳入的參數 N. 因此 Roomtype 這個欄位如果沒填或是填入的 String長度大於 6, 則會顯示如下的錯誤:[Required]
[RegularExpression("[A-Z][0-9]{9}")]
public string ID { get; set; }
除了標準 Validation 的 DataAnnotation之外, DataAnnotation也可以客製化, 有些比較單純的資料關聯性的商業邏輯驗證, 就可以透過客製化的 DataAnnotation 來做驗證. 在 .NET 上客製 DataAnnotation, 相對來說算是比較簡單的, 基本上有兩個步驟: 一是繼承 ValidationAttribute 這個 Class, 二是改寫 IsValid 這個 Method. 下面這個例子, 我們對於 Room 物件加上限制條件, “如果 Room 物件的 Roomtype 是 Beach 的話, 則 Rate 必須大於 500”. 要實作這個驗證的 Annotation, 首先我們要先建立一個新的 Class, 稱之為 ScenicRoom, 程式碼如下using System;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
{
class ScenicRoom : ValidationAttribute
{
public ScenicRoom() { }
protected override ValidationResult
IsValid(object value,
ValidationContext
validationContext)
{
Room room = (Room)
validationContext.ObjectInstance;
if (room.Roomtype == "Beach" &&
room.Rate <= 500)
{
return new ValidationResult(
"Beach room must > 500");
}
return ValidationResult.Success;
}
}
}
ScenicRoom 這個 Class 要繼承 ValidationAttribute, 並且要重新改寫 IsValid 這個 Method. IsValid 這個 Method 有兩個參數, 第一個參數是要被驗證的值, 在下面程式碼的這個例子指的是 Rate 這個變數的值. 第二個參數則是執行驗證的環境. 在這個例子中, 我們是透過 ValidationContext 的物件 validationContext來取得 Room 的物件, 然後再對這個 Room 物件的 Roomtype 及 Rate 做驗證. 在完成客製化 DataAnnotation 的 Class 之後, 只需要把它加到要驗證的變數宣告之前即可, 如下面的程式所示.當使用如下的頁面來新增(或修改)一個 Room 的物件時, 因為這個 Room 物件的 Roomtype 是 Beach, 但是 Rate 的值是 200, 也就是IsValid 第一個參數傳進來的值是 200, 而這個值小於等於 500, 因此會顯示出錯誤.using System; using System.ComponentModel.DataAnnotations; using System.Collections.Generic; public partial class Room { [Required] public string RoomID { get; set; } [Required] [StringLength(6)] public string Roomtype { get; set; } [ScenicRoom] public Nullable<int> Rate { get; set; } }