Fluent Validation in ASP.Net MVC with Example

  Total Views : 1821
  Comments : 2
 
  Keywords : Using fluent validation in asp.net mvc with example, Asp.net mvc validation using fluent validation, Implement model validations in asp.net mvc using fluent validation framework Example

Generally fluent Validation is a validation library for .NET and it uses lambda expressions for building validation rules for your business objects. 

 

If you want to do simple validation in asp.net mvc application then data annotations validation is good but in case if you want to implement complex validation then you need to use Fluent Validation. Now we will learn using fluent validation in ASP.NET MVC 4 with example.

Create Asp.Net MVC Application

Let’s first create a basic asp.net Mvc 4 application with name FluentValidationMVC for that Open visual studio studio àGo to File àSelect New àSelect Project like as shown below 

 

create new asp.net mvc project from visual studio 2012

 

 After that you will see new dialog will pop up for selecting your Template and Project type. From Templates select Visual C# à inside that select Web and then project type select ASP.NET MVC 4 Web Application and here we are giving name as “FluentValidationMVC” then finally click on ok button

 

create fluent validation example in asp.net mvc

 

After naming it just click on OK. After that a new dialog will popup for selecting template. in that select Basic template and click ok.

 

select-basic-template-for-fluent-validation-example-in-aspnet-mvc

 

After creating application our project structure like as shown below 

 

Fluent Validation Application structure in asp.net mvc application

 

After creating application now let's add Fluent Validation in your project. 

Adding Fluent Validation in Application

For adding Fluent Validation in project right click on your Project and select Manage NuGet Packages.

 

select manage nuget package to install fluent validation in asp.net mvc application

 

After selecting a NuGet search dialog will popup inside NuGet dialog in search box type Fluent Validation. After searching there is first link appear of Fluent Validation which is created by Jeremy Skinner like as shown below 

 

install fluent validation in asp.net mvc application

 

Now click on install button after installing it will show a green correct mark image

 

installation completed for fluent validation in asp.net mvc application

 

After completing with installation now let’s add a Model.

Adding Model in Fluent Validaiton Application

For adding model just right click on Model folder àselect Add àthen inside that select Class in below image you can see the process. 

 

Add new model in fluent validations asp.net mvc application

 

After Clicking on class Add New item dialog will popup with class select and asking for class name here we are going to enter class name as “Student

 

Give name to model in fluent validation asp.net mvc application

 

After entering class name click on Add button. A Student Model is added to your project with some default code like as shown below

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

namespace FluentValidationMVC.Models

{

public class Student

{

 

}

}

Now let’s add properties to this Student Model.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

namespace FluentValidationMVC.Models

{

public class Student

{

public int StudentID { get; set; }

public string StudentName { get; set; }

public DateTime StudentDOB { get; set; }

public string StudentEmailID { get; set; }

public decimal StudentFees { get; set; }

public string StudentAddress { get; set; }

public string Password { get; set; }

public string ConfirmPassword { get; set; }

}

}

Adding StudentValidator class

After adding properties now we are going to add another class with name StudentValidator this class will contain all validation rule of fluent Validation. Here we are going to add this Class to in Model folder.

 

New class to validate in asp.net mvc fluent validation

 

After adding StudentValidator class here is Model folder view

 

Fluent Validation Application structure in asp.net mvc application

 

Our StudentValidator class is added to project with some default code that will be like as shown below

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

namespace FluentValidationMVC.Models

{

public class StudentValidator

{

 

}

}

Inheriting AbstractValidator

Now we will inherit a class AbstractValidator and going to pass a parameter of Student Model to it. Here AbstractValidator is a base class for entity validator classes. Following is the code snippet after adding inherit property

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using FluentValidation;

 

namespace FluentValidationMVC.Models

{

public class StudentValidator : AbstractValidator<Student>

{

 

}

}

Adding Rule in Fluent Validation Application

Now going to create a Constructor inside this class add Rule in it. For writing rule we are going to use Lambda expression of Linq.

First we will write on Not Empty rule. Here we wrote a rule for checking StudentName which is a Model property and it is empty or not. In case if StudentName is empty then we need to send an error Message what we given. Our code snippet will be like as shown below 

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using FluentValidation;

 

namespace FluentValidationMVC.Models

{

public class StudentValidator : AbstractValidator<Student>

{

public StudentValidator()

{

RuleFor(x => x.StudentName).NotEmpty().WithMessage("Student Name is required");

}

}

}

Here we written NotEmpty rule for each properties. Following is the code snippet with all properties rules

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using FluentValidation;

 

namespace FluentValidationMVC.Models

{

public class StudentValidator : AbstractValidator<Student>

{

public StudentValidator()

{

RuleFor(x => x.StudentName).NotEmpty().WithMessage("Student Name is required");

RuleFor(x => x.StudentDOB).NotEmpty().WithMessage("Student DOB is required");

RuleFor(x => x.StudentEmailID).NotEmpty().WithMessage("Student EmailID is required");

RuleFor(x => x.StudentFees).NotEmpty().WithMessage("Student Fees is required");

RuleFor(x => x.StudentAddress).NotEmpty().WithMessage("Student Address is required");

RuleFor(x => x.Password).NotEmpty().WithMessage("Password is required");

RuleFor(x => x.ConfirmPassword).NotEmpty().WithMessage("Confirm Password is required");

}

}

}

Validating Age (Date)

In this validation we will validate students age from Birth date and give error message if it's age is less that 21. For that we created a Boolean Method which take DateTime as input and validate age and return Boolean value according to it.

AgeValidate Method

Following is the agevalidate method which we created in asp.net mvc application.

 

private bool AgeValidate(DateTime value)

{

DateTime now = DateTime.Today;

int age = now.Year - Convert.ToDateTime(value).Year;

 

if (age < 21)

{

return false;

}

else

{

return true;

}

}

Rule for StudentDOB

Here we passed that Age validate method to rule

 

RuleFor(x => x.StudentDOB)

.Must(AgeValidate)

.WithMessage("Invalid date student age must be 21 or greater than 21");

After validating date now we will validate Email Address

Validating EmailID (Email Address)

For validating Email address there is built in method called as EmailAddress() you can see below code snippet for it.

 

RuleFor(x => x.StudentEmailID)

.EmailAddress()

.WithMessage("Student EmailID is required");

Validating Fees (InclusiveBetween)

Validation will fail if the value of the property is outside of the specified range. The range is inclusive.

 

RuleFor(x => x.StudentFees)

.InclusiveBetween(0, 5000)

.WithMessage("Student Fees is not Valid");

Validating StudentAddress (Length)

Validation will fail if the length of the string is outside of the specified range. The range is inclusive. 

 

RuleFor(x => x.StudentAddress)

.Length(20, 250)

 .WithMessage("Address must be between 20 to 250 words");

Comparing Password (Equal)

Validation will fail if the value returned by the lambda is not equal to the value of the property.

 

RuleFor(x => x.ConfirmPassword)

.Equal(x => x.Password)

.WithMessage("Password do not Match");

After completion of adding rules here is complete view of StudentValidator.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using FluentValidation;

 

namespace FluentValidationMVC.Models

{

public class StudentValidator : AbstractValidator<Student>

{

public StudentValidator()

{

RuleFor(x => x.StudentName)

.NotEmpty()

.WithMessage("StudentName is required");

 

RuleFor(x => x.StudentDOB)

.NotEmpty()

.WithMessage("StudentDOB is required");

 

RuleFor(x => x.StudentDOB)

.Must(AgeValidate)

.WithMessage("Invalid date student age must be 21 or greater than 21");

 

RuleFor(x => x.StudentEmailID)

.NotEmpty()

.WithMessage("Student EmailID is required");

 

RuleFor(x => x.StudentEmailID)

.EmailAddress()

.WithMessage("Student EmailID is required");

 

RuleFor(x => x.StudentFees)

.NotEmpty()

.WithMessage("StudentFees is required");

 

RuleFor(x => x.StudentFees)

.InclusiveBetween(0,5000)

.WithMessage("Student Fees is not Valid");

 

RuleFor(x => x.StudentAddress)

.NotEmpty()

.WithMessage("StudentAddress is required");

 

RuleFor(x => x.StudentAddress)

.Length(20, 250)

.WithMessage("Address must be between 20 to 250 words");

 

RuleFor(x => x.Password)

.NotEmpty()

.WithMessage("Password is required");

 

RuleFor(x => x.ConfirmPassword)

.NotEmpty()

.WithMessage("ConfirmPassword is required");

 

RuleFor(x => x.ConfirmPassword)

.Equal(x => x.Password)

.WithMessage("Password do not Match");

}

 

private bool AgeValidate(DateTime value)

{

DateTime now = DateTime.Today;

int age = now.Year - Convert.ToDateTime(value).Year;

 

if (age < 21)

{

return false;

}

else

{

return true;

}

}

}

}

Adding Controller in Fluent Validation Application

For adding Controller Just Right click on Controller Folder inside that select Add and then select Controller.

 

Adding new controller in asp.net mvc database first application

 

After clicking on Controller new dialog will popup with name Add Controller give name as Default1Controller and In Template select “Empty MVC controller” and finally click on Add button that will be like as shown below

 

give controller name in asp.net mvc fluent validation example

 

Here is our Default1Controller code and we made some manual configuration by adding Action Selector [HttpGet], [HttpPost] with a New Action Method Index with Student model parameter as input.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using FluentValidation.Results;

using FluentValidationMVC.Models;

 

namespace FluentValidationMVC.Controllers

{

public class Default1Controller : Controller

{

[HttpGet]

public ActionResult Index()

{

return View();

}

[HttpPost]

public ActionResult Index(Student objStudent)

{

return View(objStudent);

}

}

}

After adding Controller now we need to access StudentValidator class. After accessing we will create object of StudentValidator class and then we will pass object to Fluent Validation (validator.Validate method). Now we will store that values in (ValidationResult result) and check validation using IsValid property.

 

if (result.IsValid)

    {

 

    }

If it is valid then it go inside this if block else it will go inside Else block in else Else block we are going to use Foreach loop for to show errors. 

 

foreach (ValidationFailure failer in result.Errors)

{

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

}

Finally here is complete Index method

 

[HttpPost]

public ActionResult Index(Student objStudent)

{

StudentValidator validator = newStudentValidator();

ValidationResult result = validator.Validate(objStudent);

if (result.IsValid)

{

}

else

{

foreach (ValidationFailure failer in result.Errors)

{

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

}

}

return View(objStudent);

}

Adding View in Fluent Validation Application

For Adding View just right click inside Index ActionResult Method and Select "Add View" to create the view template for our Index form. Here in below snapshot we selected View engine as Razor and we are going to create a strongly type view for that I have selected Model class Student and we want to create an input form for that I have selected Create in Scaffold template finally click on Add button. 

 

add view to controller in asp.net mvc application

 

After adding view here below is a complete View of Index.cshtml which is generated.

 

@model FluentValidationMVC.Models.Student

 

@{

ViewBag.Title = "Index";

}

<h2>Index</h2>

@using (Html.BeginForm()) {

@Html.ValidationSummary(true)

<fieldset>

<legend>Student</legend>

<div class="editor-label">

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

</div>

<div class="editor-field">

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

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

</div>

<div class="editor-label">

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

</div>

<div class="editor-field">

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

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

</div>

 

<div class="editor-label">

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

</div>

<div class="editor-field">

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

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

</div>

<div class="editor-label">

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

</div>

<div class="editor-field">

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

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

</div>

<div class="editor-label">

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

</div>

<div class="editor-field">

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

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

</div>

<div class="editor-label">

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

</div>

<div class="editor-field">

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

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

</div>

<div class="editor-label">

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

</div>

<div class="editor-field">

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

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

</div>

<p>

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

</p>

</fieldset>

}

 

<div>

@Html.ActionLink("Back to List", "Index")

</div>

@section Scripts {

@Scripts.Render("~/bundles/jqueryval")

}

Now just run application and entering URL http://localhost:####/ Default1/index  to access page. Here is the output of fluent validation asp.net application before entering validate data.

 

Fluent Validation Application output before entering validate data

 

Here is the output of fluent validation asp.net application after entering invalid data.

 

output of fluent validation asp.net application after entering invalid data.

 

Here is output of fluent validation asp.net application after entering valid data.

 

output of fluent validation asp.net application after entering valid data.

 

This is how we can use fluent validation in asp.net mvc to implement custom validations in applications.

 Comments (2)

  • Nitesh Singh tutlane registered profile image
     
    Nitesh Singh   Reply

    Very well ex|plain sir.....Thanks for share

     Mar 15, 2016
  • Quoc Do tutlane registered profile image
     
    Quoc Do   Reply

    I think you should use [Validator(typeof (StudentValidator))] above class Student what you had defined so that you don't need defined StudentValidator in your controller, It will work well

     Nov 02, 2016

Leave a comment

  • Default Tutlane User