Tuesday, 22 October 2013

Defining self-validation models in asp.net mvc using (IValidatableObject)

There are several ways to add validation to a model and one of the ways is make a model to self validate itself. This is usually done when you want to customize the validation of a particular model and it aides in composition of the model. But one of the major down side of this type of validation is that it reduces re-usability as it tightly couples the validation code to the model.

In this article we are going to have a look at how to add self validation to a model. Adding self validation to a model is actually very simple and just involves implementing IValidatableObject located in System.ComponentModel.DataAnnotations. This interface only has one method called Validate that takes in a ValidationContext object and returns an IEnumerable<ValidationResult> for the model being validated. This method is usually called after the model binder has assigned values to all the properties in the model.

For our example we are going to use our Login model from the previous article and add self validation to it by implementing an IValidatableObject.

public partial class Login : IValidatableObject
{
      public string Username{get; set;} 

      public string Password{get; set;}

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
    var errors  =  new List<ValidationResult>();

   if(string.IsNullOrEmpty(Username))
  {
      var result = new ValidationResult("Username is required!");
      errors.Add(result);
  }

   if(string.IsNullOrEmpty(Password))
   {
      var result = new ValidationResult("Password is required!");
      errors.Add(result);
   }
    
   return errors;
}

}

From the code above we can see that adding self validation to a model is actually very simple and it sits very nicely with the Mvc design pattern but it has only one downside in that you cannot reuse the validation code.

No comments:

Post a Comment