ASP.NET MVC: Self Validating Model objects

Posted by: Mahesh Sabnis , on 2/6/2015, in Category ASP.NET MVC
Views: 57292
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; }
    public string Name { get; set; }
    public string Address { get; set; }
    public DateTime BirthDate { get; set; }
    public int Income { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        var pIncome = new[] { "Income" };
            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());

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" })

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:


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

Download the entire source code of this article (Github)

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Mahesh Sabnis is a DotNetCurry author and a Microsoft MVP having over two decades 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), and Front-end technologies like Angular and React. Follow him on twitter @maheshdotnet or connect with him on LinkedIn

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!