Validation Validation
Fluent Validation In Validation
Introduction
Validation is an important part of any web application. We have several approaches to implementing validation in ASP.NET MVC applications such as Data Annotation and 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 can use when you want to treat validation logic as separate from the 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 so it has an advantage over data annotation.
This library is managed at GitHub and its also available as a NuGet package, so it's easy to add in a web application. Before moving to an example I would like to recommend you to have a look at my previous validation articles over ASP.NET MVC.
Validation is an important part of any web application. We have several approaches to implementing validation in ASP.NET MVC applications such as Data Annotation and 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 can use when you want to treat validation logic as separate from the 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 so it has an advantage over data annotation.
This library is managed at GitHub and its also available as a NuGet package, so it's easy to add in a web application. Before moving to an example I would like to recommend you to have a look at my previous validation articles over ASP.NET MVC.
- ASP.NET MVC Server-Side Validation
- ASP.NET MVC Client-Side Validation
- ASP.Net MVC Validation Using Fluent Validation
Using the CodeI will create a UserViewModel model (UserViewModel class under Models folder) that has three properties, “Name”, "Email" and "Password" as in the following code snippet:
- namespace FluentValidationApplication.Models
- {
- public class UserViewModel
- {
- public string Name { get; set; }
- public string Email { get; set; }
- public string Password { get; set; }
- }
- }
PM> FluentValidation
PM> FluentValidation.MVC5
Then I will create a validator class UserViewModelValidator for the UserViewModel model under the "Validation" folder, but you can create it anywhere in an application for validation rules on UserViewModel properties. I used three rules, one is not empty and the second validates an email address and third for password length. The following code snippet shows the UserViewModelValidator class.
- using FluentValidation;
- using FluentValidationApplication.Models;
- namespace FluentValidationApplication.Validation
- {
- public class UserViewModelValidator : AbstractValidator<UserViewModel>
- {
- public UserViewModelValidator()
- {
- RuleFor(x => x.Name).NotEmpty().WithMessage("*Required");
- RuleFor(x => x.Password).NotEmpty().WithMessage("*Required").Length(6, 10);
- RuleFor(x => x.Email).EmailAddress().WithMessage("Not Valid").NotEmpty().WithMessage("*Required");
- }
- }
- }
- using FluentValidation;
- using FluentValidationApplication.Models;
- using System;
- using System.Collections.Generic;
- namespace FluentValidationApplication.Validation
- {
- public class ValidatorFactory : ValidatorFactoryBase
- {
- private static Dictionary<Type, IValidator> validators = new Dictionary<Type, IValidator>();
- static ValidatorFactory()
- {
- validators.Add(typeof(IValidator<UserViewModel>), new UserViewModelValidator());
- }
- public override IValidator CreateInstance(Type validatorType)
- {
- IValidator validator;
- if (validators.TryGetValue(validatorType, out validator))
- {
- return validator;
- }
- return validator;
- }
- }
- }
Now we need to execute this validator factory constructor once when the application runs, so we will create its instance in the Global.asax.cs file as in the following code snippet.
- using FluentValidation.Mvc;
- using FluentValidationApplication.App_Start;
- using FluentValidationApplication.Validation;
- using System.Web.Mvc;
- using System.Web.Optimization;
- using System.Web.Routing;
- namespace FluentValidationApplication
- {
- public class MvcApplication : System.Web.HttpApplication
- {
- protected void Application_Start()
- {
- AreaRegistration.RegisterAllAreas();
- BundleConfig.RegisterBundles(BundleTable.Bundles);
- ValidationConfiguration();
- RouteConfig.RegisterRoutes(RouteTable.Routes);
- }
- private void ValidationConfiguration()
- {
- FluentValidationModelValidatorProvider.Configure(provider =>
- {
- provider.ValidatorFactory = new ValidatorFactory();
- });
- }
- }
- }
- using FluentValidationApplication.Models;
- using System.Web.Mvc;
- namespace FluentValidationApplication.Controllers
- {
- public class UserController : Controller
- {
- [HttpGet]
- public ActionResult AddUser()
- {
- UserViewModel model = new UserViewModel();
- return View(model);
- }
- [HttpPost]
- public ActionResult AddUser(UserViewModel model)
- {
- if(ModelState.IsValid)
- {
- //Implement your application logic
- }
- return View(model);
- }
- }
- }
- @model FluentValidationApplication.Models.UserViewModel
- <div class="panel panel-primary">
- <div class="panel-heading panel-head">Add User</div>
- <div class="panel-body">
- @using (Html.BeginForm())
- {
- <div class="form-horizontal">
- <div class="form-group">
- @Html.LabelFor(model => model.Name, new { @class = "col-lg-2 control-label" })
- <div class="col-lg-9">
- @Html.TextBoxFor(model => model.Name, new { @class = "form-control" })
- @Html.ValidationMessageFor(model=>model.Name)
- </div>
- </div>
- <div class="form-group">
- @Html.LabelFor(model => model.Email, new { @class = "col-lg-2 control-label" })
- <div class="col-lg-9">
- @Html.TextBoxFor(model => model.Email, new { @class = "form-control" })
- @Html.ValidationMessageFor(model => model.Email)
- </div>
- </div>
- <div class="form-group">
- @Html.LabelFor(model => model.Password, new { @class = "col-lg-2 control-label" })
- <div class="col-lg-9">
- @Html.PasswordFor(model => model.Password, new { @class = "form-control" })
- @Html.ValidationMessageFor(model => model.Password)
- </div>
- </div>
- <div class="form-group">
- <div class="col-lg-9"></div>
- <div class="col-lg-3">
- <button class="btn btn-success" id="btnSubmit" type="submit">
- Submit
- </button>
- </div>
- </div>
- </div>
- }
- </div>
- </div>
Figure: 1: Validation rules implemented on input fields
Download
You can download a complete solution for FluentValidation in ASP.NET MVC 5 using Dependency Injection from here
Validation Validation
Reviewed by Unknown
on
10:34 AM
Rating:



No comments: