.NET life

HUGON Jérôme
Microsoft Certified Technology Specialist Microsoft Certified Application Developer Microsoft Certified Professional

The IValidatableObject interface

MVC 3

Category MVC 3  | Publication Date : 3/29/2011

The IValidatableObject interface introduced with version 4 of .NET framework is supported by MVC 3. It allows a level validation of the model and allows you to return specific messages about the state of the model.

Be careful, validation interface IValidatableObject is triggered if there are no errors in the properties. Indeed, MVC 3 performs a first step validating properties before the validation objects. In case of errors in the properties, there will be no outbreak of validation at the object with the interface IValidatableObject.

 

Implement IValidatableObject interface

The IValidatableObject interface is quite simple to implement, there is only one method: Validate which return an object of type IEnumerable<ValidationResult>:

 

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

namespace MvcSamples.Models
{
    public class TestModel : IValidatableObject
    {
       public string Title { get; set; }
       public string Description { get; set; }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            // Do validation stuff here
        }
    }
}

 

Integrate validation logic in the model

You can make the validation regarding your logic into the method Validate and return one or more error messages. Here is an example of implementation which validate that each property of the model is not null:

 

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
    if (Title == null)
    {
        yield return new ValidationResult("The title is mandatory.");
    }
    if (Description == null)
    {
        yield return new ValidationResult("The description is mandatory.");
    }
}

 

The controller

In the controller, the action that receives the response from the client can perform a test on the property IsValid from the property ModelState of the controller to determine if the model has passed all validation steps or not. You then integrate the logic of forwarding:

 

[HttpPost]
public ActionResult Create(TestModel model)
{
    if (!ModelState.IsValid)
    {
        return View();
    }
    else
    {
        return View("Index");
    }
}

 

Notice that to show the errors in the view, there is no specific method to call. The view is returned in a conventional manner.

 

The vue

Here is the code of the view where the creation form is display, nothing is special:

 

@model MvcSamples.Models.TestModel

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>TestModel</legend>

        @Html.EditorForModel()

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

 

Here is the render in the browser after send the form without any data in the fields:

MVC3 - IValidatableObject - 1

 

Customize the display of errors

You also have the option when instantiating the object ValidationResult to define the fields involved in specifying a collection of type string with the name of the properties. This will display the error next to the fields instead of displaying it in the error summary page:

 

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (Title == null || Description == null)
    {
        yield return new ValidationResult("All fields are mandatory.");
    }
    if (Title == null)
    {
     yield return new ValidationResult("*", new string[] { "Title" });
    }
    if (Description == null)
    {
        yield return new ValidationResult("*", new string[] { "Description" });
    }
}

The rendering of the views is automatically updated without any changes in the views itself:

MVC3 - IValidatableObject - 2


Related articles

TechDays 2011 - What's new in ASP.NET MVC 3

MVC 3

Category MVC 3  | Publication Date : 4/16/2011