ASP.Net MVC Validation Using Fluent Validation

This article explains how to implement ASP.NET MVC validation using Fluent Validation. Fluent validation is a small validation library for .NET that uses a Fluent interface and lambda expressions for building validation rules for your business objects.  Fluent validation is one way of setting up dedicated validator objects, that you would use when you want to treat validation logic as separate from business logic. The Aspect-Oriented Programming (AOP) paradigm enables separation of cross-cutting concerns within a system, and validation is one such concern. Separating validation helps clean up your domain code and make it more cohesive, as well as giving you a single place to look for validation logic.

I create a Customer model (Customer class under Models folder) that has two properties, one is “Email” and another is “Name” as in the following code snippet:

namespace MvcValidation.Models

{

    public class Customer

    {

        public string Name { get; set; }

        public string Email { get; set; }

    }

}

Now I install the Fluent validation Nuget package in the application so I can use Fluent validation rules.

Figure 1.1 Install FluentValidation NuGet package

After that I create a validator class for the Customer model under the “Validators” folder but you can create it anywhere in an application for validation rules on Customer properties. I used two rules, one is not empty and another validates an email address.

using FluentValidation;

using MvcValidation.Models;

 

namespace MvcValidation.Validators

{

    public class CustomerValidator : AbstractValidator<Customer>

    {

        public CustomerValidator()

        {

            RuleFor(x => x.Name).NotEmpty().WithMessage(“Name is required”);

            RuleFor(x => x.Email).NotEmpty().WithMessage(“Email is required”);

            RuleFor(x => x.Email).EmailAddress().WithMessage(“Email is not valid”);               

        }

    }

}

After that, you need to create a controller’s action methods; these render views on the UI and binds a model with the view. So let’s create a controller with two action methods; these handle both request types (GET and POST) respectively.

using System.Web.Mvc;

using FluentValidation.Results;

using MvcValidation.Models;

using MvcValidation.Validators;

 

namespace MvcValidation.Controllers

{

    public class CustomerController : Controller

    {

        public ActionResult Index()

        {

            return View();

        }

        [AcceptVerbs(HttpVerbs.Post)]

        public ActionResult Index(Customer model)

        {

            CustomerValidator validator = new CustomerValidator();

            ValidationResult result = validator.Validate(model);

            if (result.IsValid)

            {

                ViewBag.Name = model.Name;

                ViewBag.Email = model.Email;

            }

            else

            {

                foreach (ValidationFailure failer in result.Errors)

                {

                    ModelState.AddModelError(failer.PropertyName, failer.ErrorMessage);

                }               

            }

            return View(model);

        }

    }

}

Thereafter I create a view (Index.cshtml) for user input under the Customer folder.

@model MvcValidation.Models.Customer

@{

    ViewBag.Title = “Index”;

}

@if (ViewData.ModelState.IsValid)

{

    <b>Name : @ViewBag.Name<br />

        Email : @ViewBag.Email

    </b>       

}

@using (Html.BeginForm())

{    

    <fieldset>

        <legend>Customer</legend>

        <div class=”editor-label”>

            @Html.LabelFor(model => model.Name)

        </div>

        <div class=”editor-field”>

            @Html.EditorFor(model => model.Name)

            @Html.ValidationMessageFor(model => model.Name)

        </div>

        <div class=”editor-label”>

            @Html.LabelFor(model => model.Email)

        </div>

        <div class=”editor-field”>

            @Html.EditorFor(model => model.Email)

            @Html.ValidationMessageFor(model => model.Email)

        </div>

        <p>

            <input type=”submit” value=”Create” />

        </p>

    </fieldset>

}

@section Scripts {

    @Scripts.Render(“~/bundles/jqueryval”)

}


Let’s run the application and test the following scenario:

1. When all fields are empty:

Figure 1.2: Validation Message when both fields are empty

2. When the Name field is empty but Email is not valid:

Figure 1.3 : Validation Message when Email is not valid

3. When both fields are valid:

Figure 1.4 All fields are valid