ASP.NET MVC > Validation

Fluent validation framework in ASP.NET MVC in ASP.NET MVC

How to implement fluent validation framework in ASP.NET MVC?


Fluent validation framework is a small validation library that uses fluent interface and lamda expressions for building validation rules in the Models. This is an extension of the default validation framework that comes with ASP.NET MVC. In this, writing validation logics are much easier than writing in default validation framework, plus it accommodates much broader types of validations.

In order to implement fluent validation, we need to plug-in fluent validation framework into our project by using “Mange NuGet Packages” by right clicking the project and selecting “Manage NuGet Packages …”.

Now write fluent into the search box that lists the Fluent related plug ins.

Clicking on Install, installs the FluentValidation framework in our project by adding FluentValidation.dll in the .bin folder.

To demonstrate how to use Fluent Validation framework, here is a new model created. Notice that we do not have any validation attribute in this model.

MODEL CODE

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace MVCTraining5.Models
{
    public class FluentModel
    {
        [Key]
  
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOpt
ion.Identity)]
        public int AutoId { get; set; }

        public string FullName { get; set; }
     
        public string EmailId { get; set; }
        
        public DateTime DateOfBirth { get; set; }

        public int Age { get; set; }
    }
}

To create validation rules for this model, we need to create a Validator class (corresponding to each model).

VALIDATOR CODE (CREATE IN ANY NEW FOLDER)

using FluentValidation;
using MVCTraining5.Models;

namespace MVCTraining5.Validation
{
    public class FluentModelValidator : AbstractValidator<FluentModel>
    {
        public FluentModelValidator()
        {
            RuleFor(model => model.FullName).NotNull(); // Required

            RuleFor(model => model.EmailId).NotNull(); // Required

            RuleFor(model => model.EmailId).EmailAddress(); // email id

            RuleFor(model => model.Age).GreaterThan(18); // greater 18
         }
     }
}

Notice that this class inherits the AbstractValidator class by passing FluentModel we just created. Now we need to write rules for fields we want to validate. In this case, we have rule for FullName, Email Id (Required), EmailId to make sure that user enters email id in correct format, Age so that user enters age that is greater than 18.

The view of this Model (FluentModel) remains same as in case of standard model that comes with scaffolding.

CONTROLLER ACTION CODE

public ActionResult FluentView(FluentModel model)
        {
            MVCTraining5.Validation.FluentModelValidator validator = new
Validation.FluentModelValidator();
            FluentValidation.Results.ValidationResult result =
validator.Validate(model);
            if (result.IsValid)
            {
                // success
                ViewBag.ResultMessage = "Validation successful!";
            }
            else
            {
                foreach(ValidationFailure failure in result.Errors)
                {
                    ModelState.AddModelError(failure.PropertyName,
failure.ErrorMessage);
                }
            }
            return View(model);
        }

The action method is slightly different as we need to validate it using FluentValidation framework. Instantiate the FluentModelValidator class and call Validate method that returns ValidationResult object with is IsValid property. If IsValid is true then validation rules for FluentModel is passed otherwise not. In the else block we are looping through each error and setting to the AddModelError so that erro displays beside each error field in the view.

Notice the above view that is showing the default error message as per the rule.

For more rules of FluentValidation and how to apply them, please visit

http://fluentvalidation.codeplex.com/documentation

 Views: 2563 | Post Order: 91



Write for us