Blog

Filter posts by Category Or Tag of the Blog section!

Using FluentValidation in MVC

Tuesday, 14 August 2012

Based on CodePlex definition: "FluentValidation is A small validation library for .NET that uses a fluent interface and lambda expressions for building validation rules for your business objects."

There is no any problem to use Asp.net MVC built-in DataAnnotation but in some cases, it's better to use FluentValidation instead. I list my reasons about which should be selected to use here.

Use DataAnnotation if :

Your system is simple and you don't have any complex validation in your user interface, in this kind of simple application you can also use fluent validation to make your model POCO and clean , but if you are using ViewModel, in this case, there is no need to do that and make project more complex by using FluentValidation.

Use FluentValidation if :

Your system is an enterprise and large-scale one and you have several layers in your application and it's needed to have cleaned and refactored code, defiantly in a system like this you have unit testing and also you use ViewModel, to do server-side validation of this system I hardly recommend to use FluentValidation. It is so important to separate validation logic from business logic, despite ViewModel usually is nothing more than some properties but it is better to make it readable. Rather than you can make your custom validators in FluentValidation easier than MVC built-in DataAnnotation, and there are some useful validators in FluentValidation such as Email, Credit Card and etc.!

So, Get FluantValidation library from the website or by Nuget and let's begin working with that.

Example one :

suppose that the BlogViewModel Class is the one that MVC uses to bind and the BlogValidation is the Validation class in this example :

 

    [Validator(typeof(BlogValidation))]
    public class BlogViewModel
    {
        public string Title { get; set; }
        public string Body { get; set; } 
    }
    public class BlogValidation : AbstractValidator<BlogViewModel>
    {
        public BlogValidation()
        {
            RuleFor(b => b.Title).NotEmpty().WithMessage("Title is Empty");
            RuleFor(b => b.Body).NotEmpty().WithMessage("Post Body is Empty");
        }
     }

 

 And in your Global.asax, you have to define the FluentValidation Configuration :

 

 protected void Application_Start()
 {
    //…
    FluentValidationModelValidatorProvider.Configure();
 }

 

And in your controller, you should do like what you have been doing before, for example

 

        public ActionResult Post()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Post(PostViewModel postViewModel)
        {
            if (ModelState.IsValid)
            {
                //call service or repository to insert the post
            }
            return View();
        }

 

Example two:

 

    [Validator(typeof(ProfileValidation))]
    public class ProfileViewModel
    {
        public string Name { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public string ConfirmPassword { get; set; }
        public int  Age { get; set; }
     }
    public class ProfileValidation : AbstractValidator<ProfileViewModel>
    {
        public ProfileValidation ()
        {
            RuleFor(p => p.Name).NotEmpty().WithMessage("Name is Empty");           
            RuleFor(p => p.Email).NotEmpty().WithMessage("Name is Empty").EmailAddress().
            WithMessage("Email format is incorrect");
            RuleFor(p => p.Password).NotEmpty().length(6,18);
            RuleFor(p => p.ConfirmPassword).NotEmpty().Equal(p=>p.Password);
            RuleFor(p => p.Age).GreaterThanOrEqualTo(DateTime.Today.AddYears(-15))
            .NotEmpty().withMessage("Enter the Age");   // guys greater than 15 years old!
         }
    }

 

Category: Software

comments powered by Disqus