DataAnnotation 自定义验证

当系统提供的不够用的时候,使用自定义。

方法步骤:(1)定义一个类继承ValidationAttribute

          (2)重写IsValid方法

 1 public class Test{
 2     [ Price(2.2)]
 3      public double Price{get;set;}
 4 }
 5 
 6 public class PriceAttribute : ValidationAttribute
 7 
 8  {
 9 
10        public double MinPrice { get; set; }  //用来接受[Price(2.2)]中2.2的这个值,系统自动赋值
11 
12         public override bool IsValid(object value) {  
13 
14        if (value == null) { 
15 
16        return true;  
17 
18         }  
19 
20         var price = (double)value;  
21 
22        if (price < MinPrice) {  
23 
24        return false;  
25 
26         }
27 
28        double cents = price - Math.Truncate(price);  
29 
30         if(cents < 0.99 || cents >= 0.995) {  
31 
32         return false;  
33 
34        } 
35 
36        return true;  
37 
38         }   
39 
40 }

 

posted on 2013-06-06 09:40  xinchuang  阅读(1104)  评论(0编辑  收藏  举报