Using Fluent Validation in Asp.Net MVC5 Application (Visual Studio 2013 RC)

Rama Sagar
Posted by in ASP.NET MVC category on for Beginner level | Points: 250 | Views : 10178 red flag
Rating: 3 out of 5  
 1 vote(s)

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.

Introduction


This article help us to learn 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 our business objects.  Fluent validation is one way of setting up dedicated validator objects, that we would use when we want to separate  validation logic from business logic.
  
Please have a look at my previous articles where i have explained other validations

 Validation using Data Annotations


Lets start using Fluent Validation

  •  Step 1  create a Asp.NEt Application using MVC Template 
         Click on Tools -> Library Package Manager ->Package Manager Console and And type the following                          command:

                  install-package FluentValidation



  •  Step 2 Lets create a Model class with the properties  as shown
namespace samplefluentvalidation.Models
{
    public class Products
    {
        public int ProductID { get; set; }
        public string ProductName { get; set; }
        public string ProductManufacturer { get; set; }
    }
}

  •   Step 3 Now create a separate class for the products model
          Create a folder named validations and create a class named ProductValidator

using FluentValidation;

namespace samplefluentvalidation.Models.Validations
{
    public class ProductValidator : AbstractValidator<Products>
    {
        public ProductValidator()
        {
            RuleFor(x => x.ProductName).NotEmpty().WithMessage("Name is required");
            RuleFor(x => x.ProductManufacturer).NotEmpty().Length(20, 250).WithMessage("Must be atleast 20 characters"); ;

        }
    }
}
  •  Step 3  Now lets Create a controller as shown
using FluentValidation.Results;
using samplefluentvalidation.Models;
using samplefluentvalidation.Models.Validations;
using System.Web.Mvc;

namespace samplefluentvalidation.Controllers
{
    public class ProductsController : Controller
    {
        //
        // GET: /Products/
        public ActionResult Index()
        {
            return View();
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(Products model)
        {
            ProductValidator validator = new ProductValidator();
            ValidationResult result = validator.Validate(model);
            if (result.IsValid)
            {
                ViewBag.ProductName = model.ProductName;
                ViewBag.ProductManufacturer = model.ProductManufacturer;
               
            }
            else
            {
                foreach (ValidationFailure failer in result.Errors)
                {
                    ModelState.AddModelError(failer.PropertyName, failer.ErrorMessage);
                }
            }
            return View(model);
        }
    }
}
  • Step 4  Now create a folder named products in views and add a view named Index and adthe below lines
@model samplefluentvalidation.Models.Products
@{
    ViewBag.Title = "Index";
}
@if (ViewData.ModelState.IsValid)
{
    <b>
       Product Name : @ViewBag.ProductName<br />
       Product Manufacturer : @ViewBag.ProductManufacturer
    </b>
}
@using (Html.BeginForm())
{
    <fieldset>
        <legend>Products</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.ProductName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ProductName)
            @Html.ValidationMessageFor(model => model.ProductName)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.ProductManufacturer)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ProductManufacturer)
            @Html.ValidationMessageFor(model => model.ProductManufacturer)
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

we have created all the model controller and views lets browse the index page and check the validations



Conclusion

so far in this Article we have learned how to use Fluent Validation in MVC5 Application..Please let me know any issues on this through your comments

Reference

http://fluentvalidation.codeplex.com

Page copy protected against web site content infringement by Copyscape

About the Author

Rama Sagar
Full Name: RamaSagar Pulidindi
Member Level: Silver
Member Status: Member,MVP
Member Since: 12/30/2012 1:51:40 AM
Country: India
ramasagar
http://www.ramasagar.com
A Software Profesional working in Microsoft .NET technologies since year 2008, and I work for Dake ACE. I am passionate about .NET technology and love to contribute to the .NET community at Dot Net Funda

Login to vote for this post.

Comments or Responses

Posted by: Sheonarayan on: 10/23/2013 | Points: 25
Hello Ram,

Thanks for the article, well explained. However could you also let us know what is the difference between normal validation using the model and fluent validation in ASP.NET MVC? In this case I noticed that we have to create one more validator class but in normal validation, we just write the validation attributes in the Model itself.

Thanks

Login to post response

Comment using Facebook(Author doesn't get notification)