Fluent Validation In ASP.NET MVC

Datetime:2016-08-23 04:40:19          Topic: ASP.NET MVC           Share

Validation is a process to validate and check the data inserted by the user in the view. ASP.NET MVC provides various mechanisms for the validation like Remote Validation, Validation using Data Annotations, Fluent Validation and Custom Validation. In this article, we will read about Fluent Validation. Fluent Validation contains .NET libraries and the validation is performed using the Lambda expression. Use Fluent Validation when you want to create some advanced and complex validation for the user data. Let’s start this session.

First go to File-> New-> Project and create ASP.NET MVC project.

Now, we will load the required libraries for Fluent Validation. For this,  Right Click on the project name and click the “Manage NuGet Packages” option. Now, insert “FluentValidation” in the search box, select the FluentValidation libraries and install this.

Now, we will create an “Employee” Class in the model, as shown below:

After creating the Employee class, we will create another class (“Employee_Validation”) and insert all the validation rules in this class. Code of Employee_Validation class is shown below:

using FluentValidation;  
using System;  
  
namespace Fluent_Validation.Models  
{  
    public class Employee_Validation: AbstractValidator<Employee>  
    {  
        public Employee_Validation()  
        {  
            RuleFor(x => x.Name).NotEmpty().WithMessage("Employee Name is required");  
            RuleFor(x => x.Mail_ID).NotEmpty().WithMessage("Employee Mail_ID is required");  
            RuleFor(x => x.DOB).NotEmpty().WithMessage("Employee DOB is required");  
            RuleFor(x => x.Password).NotEmpty().WithMessage("Employee Password is required");  
            RuleFor(x => x.Confirm_Password).NotEmpty().WithMessage("Employee Password is required");  
            RuleFor(x => x.Confirm_Password).Equal(x => x.Password).WithMessage("Password Don't Match");  
  
            RuleFor(x => x.Mail_ID).EmailAddress().WithMessage("Email Address is not correct");  
            RuleFor(x => x.DOB).Must(Validate_Age).WithMessage("Age Must be 18 or Greater");  
            RuleFor(x => x.Password).Must(PAssword_Length).WithMessage("Password Length must be equal   or greater than 8");  
  
  
  
        }  
  
        private bool PAssword_Length(string  pass_)  
        {  
             
  
            if (pass_.Length<8)  
            {  
                return false;  
            }  
            else  
            {  
                return true;  
            }  
        }  
  
        private bool Validate_Age(DateTime Age_)  
        {  
            DateTime Current = DateTime.Today;  
            int age = Current.Year - Convert.ToDateTime(Age_).Year;  
  
            if (age < 18)  
            {  
                return false;  
            }  
            else  
            {  
                return true;  
            }  
        }  
    }  
}  

To implement Fluent Validation, we are required to inherit “AbstractValidator” class, which is a base class for Fluent Validation. Put all the required validation rules in Employee_Validation constructor. RuleFor method is used to define the validation rule for a class property and a property is accessed by Lambda expression. The various types of validation can be implemented on the properties like NotEmpty, comparison, Must, NotEqual and other types of the validations. After implementing all the required validation, we create a controller.

To add a controller, right click on Controller folder, create an empty Controller and name it “EmployeeController”.

In this class, we will create an index action for HttpPost action selector. In this index action method, we will create the object of Employee_Validation class, pass the Student Model object into the Validate method and retrieve the result in ValidationResult object. Check for the error, if ValidationResult object contains any error, it will return the error list and this error list will be visible in the view section.

After creating the controller, we will add the view for the index action method.

Now, check the view. You will find that all the fields are created for each property of Employee model.

Now, run the Application.

After running the Application, insert some data and click “create” button.

When we submit the above form, the following errors will generate:

If we insert the valid data, no error will generate.

Conclusion

Use Fluent Validation if you want to implement complex or high level validation. For Normal Validation, you can prefer Data Annotation Validation. 





About List