Pranay Rana: Complex Custom Validation Attribute Specific to Entity

Saturday, March 7, 2015

Complex Custom Validation Attribute Specific to Entity

System.Componentmodel.DataAnnotation NameSpace

System.Componentmodel.DataAnnotation is namespace in .net framework provide set of the attribute classes. This attribute classes used for decorating property of the user defined entity and validate entity.

Find more about each class on MSDN : https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations%28v=vs.95%29.aspx

ValidationAttribute: -

Most of all required attributes for validation is provided in the DataAnnotation namespace but there are some complex validation required to validate entity required to define by developer of itself.

ValidationAttribute is class in DataAnnotation namespace allow to create custom attribute as per the need to developer to validate entity.

Following is implementation of custom validation attribute:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public sealed class AccountBalaceCheckAttribute : ValidationAttribute
{
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            ValidationResult result = ValidationResult.Success;
            string[] memberNames = new string[] { validationContext.MemberName };

            decimal val = Convert.ToDecimal(value);

            BankAccount account = (BankAccount)validationContext.ObjectInstance;

            if (account.AcType == BankAccount.AccountType.Saving && val < 500)
                result = new ValidationResult(string.Format(this.ErrorMessage, 500),memberNames);
            else if (account.AcType == BankAccount.AccountType.Current && val < 1000)
                result = new ValidationResult(string.Format(this.ErrorMessage, 1000), memberNames);


            return result;
        }
} 

How to use it

 
public class BankAccount
{

   public enum AccountType
   {
      Saving,
      Current
   }

   public AccountType AcType { get; set; }

   [AccountBalaceCheckAttribute(ErrorMessage = "Account Balance should have value more than {0}")]
   public double AccountBalance { get; set; }
}

In this example attribute is defined for the specific entity BankAccount entity. Requirement for defining this attribute is “Based on value of AccountType , account should hold minimum balance.”

So for that here, BankAccount object is accessed in IsValid method and then by checking value of the Account type attribute validates AccountBalance value.

Other Things to note here are :
  1. Attribute class is Sealed and Derived from the ValidationAttribute.
  2. Custom attribute class override IsValid method of the base ValidationAttribute class.
  3. Attribute can be used for property and not allowed to define attribute multiple time on property.
To find how to define attribute not specific to entity follow MSDN: https://msdn.microsoft.com/en-us/library/cc668224%28v=vs.140%29.aspx

No comments:

Post a Comment