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:
  1. public class MyClass {
  2. // ... more code
  3. [MagicNumber(ErrorMessage = "Magic Number is not correct")]
  4. public int MyData { get; set; }
  5. // ... more code
  6. }

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

Done. Simple.
Additional reading:

No comments: