Sunday, March 3, 2013

Creating Custom Validation Attribute

In this post, I will outline steps in making custom validation attribute. This is the first post of a series, which eventually will go all the way to making the validation to be able to evaluated in the client side. But, let's not get too far ahead - first we need to make our custom validator.

In this example, I have a simple validator that need to evaluate whether the value of the field "MyData" is equal to the "37".

Our class:
public class MyClass {
   // ... more code
   [MagicNumber(ErrorMessage = "Magic Number is not correct")]
   public int MyData { get; set; }
   // ... more code
}

Our custom validator:
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
sealed public class MagicNumberAttribute : ValidationAttribute {
   public override bool IsValid(object value) {
      var num = int.Parse(value.ToString());
      return num == 37;
   }
}

Done. Simple.
Additional reading:

No comments: