DotNetCurry Logo

ASP.NET MVC: Self Validating Model objects

Posted by: Mahesh Sabnis , on 2/6/2015, in Category ASP.NET MVC
Views: 31119
Abstract: This article shows how to create Self Validating Model Objects in ASP.NET MVC

ASP.NET MVC supports the DRY (Don’t Repeat Yourself) principle where you specify the behavior once and it reflects at multiple places in the application. Model Validation is one such example where you can specify validation rules in the model class and enforce the rules everywhere else in the application.

 

ASP.NET MVC provides multiple ways of model validations e.g. using Custom DataAnnotations, Remote validation etc. In Custom DataAnnotations we need to create a separate class derived from the ValidationAttribute base class. More information about Custom DataAnnotations can be grabbed from here. The Remote feature provides Asynchronous Validation on the Model property. To implement asynchronous validations using Remote, we need to write action method in MVC controller that returns a JsonResult.

But what if that we want to provide validation check logic for the Model class? E.g. in case of Employee model, salary property in the Model should not be negative or for a Person model, the BirthDate should not be a future date and so on. In this case we must provide self-validation behavior for the model class. To do so, we can use the IValidatableObject interface under System.ComponentModel.DataAnnotation namespace. This interface provides the Validate interface with ValidationContext input parameter. This parameter defines the context in which validations are checked. The method has IEnumerable<ValidationResult> as output parameter. This provides error messages generated for properties from the model class.

Let’s see an example.

Step 1: Open Visual Studio 2013, and create a new empty ASP.NET MVC application. Name it as MVC5_IValidation. In this project, add the following code in the Models folder by adding class file.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace MVC5_IValidation.Models
{
public class Person : IValidatableObject
{
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    [Required]
    public string Address { get; set; }
    [Required]
    public DateTime BirthDate { get; set; }
    [Required]
    public int Income { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var pIncome = new[] { "Income" };
        if(Income<0)
        {
            yield return new ValidationResult("Income cannot be negative",pIncome);
        }
        var pName = new[] {"Name"};
        if (Name.Length > 40)
        {
            yield return new ValidationResult("Name cannot be such huge in length",pName);
        }
        var pBDate = new[] {"BirthDate"};
        if (BirthDate > DateTime.Now)
        {
            yield return new ValidationResult("Sorry Future Date cannot be accepted.",pBDate);
        }
        
    }
}
}

The Person model class implements IValidatableObject with its Validate method. The method contains logic for validating Income and BirthDate. The array declared in the method is used to associate the validation result for the model property, on which validation is checked. Here we have made the Model object as a self Validatable object and the advantage of this approach is that we need not write a separate class for validation checks.

Step 2: In the Controllers folder, add a new empty MVC Controller of the name PersonController. In the controller, add the following code for Create Action methods:

public ActionResult Create()
{
    return View(new Person());
}


[HttpPost]
public ActionResult Create(Person p)
{
    return View(p);
}

Step 3: Scaffold a Create View from the Create method with the Person Model class. In the view we already have the ValidationMessageFor Html helper method as shown here:

<div class="form-group">
    @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
    </div>
</div>

Run the application and enter values for Name, BirthDate, and Income. Click on the Create button, if values are invalid, error messages will be displayed as shown here:

aspnetmvc-model-validation

Conclusion: The IValidatableObject interface helps to configure the Model object with Self-Validating behavior.

Download the entire source code of this article (Github)

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
Mahesh Sabnis is a DotNetCurry author and Microsoft MVP having over 17 years of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions). Follow him on twitter @maheshdotnet


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Fabio Ambrozio on Wednesday, April 22, 2015 2:41 AM
Thanks.  It's a nice tuto!