ASP.NET MVC采用System.ComponentModel.DataAnnotations提供的元数据验证机制对Model实施验证,我们可以在Model类型或者字段/属性上应用相应的ValidationAttribute。但是在默认情况下,对于同一个类型的ValidationAttribute特性只允许一个应用到目标元素上——即使我们将AllowMultiple属性设置为True。这篇文章的目的就是为了解决这个问题。[源代码从这里下载]

为了演示在相同的目标元素(类、属性或者字段)应用多个同类的ValidationAttribute,我定义了一个名称为RangeIfAttribute特性用于进行“有条件的区间验证”。如下面的代码片断所示,RangeIfAttribute是RangeAttribute的子类,应用在上面的AttributeUsageAttribute特性的AllowMultiple 属性被设置为True。RangeIfAttribute定义了Property和Value两个属性,分别表示被验证属性/字段所在类型的另一个属性名称和相应的值,只有当指定的属性值与通过Value属性值相等的情况下我们在真正进行验证。具体的验证逻辑定义在重写的IsValid方法中。

true)]
class RangeIfAttribute: RangeAttribute
   3: {
string Property { get; set; }
string Value { get; set; }
double maximum)
base(minimum, maximum)
   8:     {
this.Property = property;
value;
  11:     }
value, ValidationContext validationContext)
  13:     {
null);
;
this.Value)
  17:         {
null;
  19:         }
value))
  21:         {
null;
  23:         }
  24:  
null;
this.FormatErrorMessage(validationContext.DisplayName), memberNames);
  27:     }
  28: }

相关文章:

  • 2022-12-23
  • 2022-01-19
  • 2021-09-05
  • 2021-09-23
  • 2022-12-23
  • 2021-06-24
猜你喜欢
  • 2022-12-23
  • 2021-08-08
  • 2022-12-23
  • 2021-08-20
  • 2022-12-23
  • 2021-07-10
相关资源
相似解决方案