How to use standard validation data annotations with custom types?

Is it possible to use the standard data annotations within the .NET framework (such as StringLength, RegularExpression, Required, etc.) with custom types?

What I want to do is something like this:

  class MyProperty<TValue>
   {
      public bool Reset { get; set; }
      public TValue Value { get; set; }
   }

   class MyClass
   {
      [Required]
      [StringLength(32)]
      MyProperty<string> Name { get; set; }

      [StringLength(128)]
      MyProperty<string> Address { get; set; }

   }

And, of course, I want the validation to act upon the "Value" property. Looking at the code of the various validation attributes it looked like they were simply calling ToString() to get a value from the object. I tried overriding ToString() and return Value as a string, but excpetions are being thrown stating that the annotation cannot cast the object (Value) to string (even though the override did just that...?).

I'm trying to avoid writing custom versions of all the various possible validators to accommodate this simple type.


You can take a look into a source code for StringLength: https://github.com/Microsoft/referencesource/blob/master/System.ComponentModel.DataAnnotations/DataAnnotations/StringLengthAttribute.cs

You can see that IsValid casts your value to string, which would fail for your custom class. But you can create your own validation attribute.

Here is an explicit to string casting option for not writing your own validator:

public static explicit operator string(MyProperty prop)
{
       return "Stuff you want to return as string";
}

Put it inside your MyProperty class.

链接地址: http://www.djcxy.com/p/9704.html

上一篇: SqlException超时未到达而过期

下一篇: 如何将标准验证数据注释与自定义类型一起使用?