Simple MVC Application using FluentValidation.MVC4

This is a simple example of MVC application using FluentValidation.MVC4.

Create a new web application MVC4.

Get the fluent validation using nuget:

Create a validation rule set class:

using FluentValidation;
using MvcFluentValidation.Models;

namespace MvcFluentValidation.ModelValidators
    public class FluentDataModelValidator : AbstractValidator<FluentDataModel>
        public FluentDataModelValidator()
           RuleFor(x => x.ValString1)
            RuleFor(x => x.ValString2)
                .Length(6, 100);

            RuleFor(y => y.ValDouble1).InclusiveBetween(40.0, 50.0);

            RuleFor(customer => customer.ApplicationSubmitted).NotEmpty().When(customer => customer.SelectedApplicationStatus > 0);

Now add the attribute to the model class: FluentDataModel

using System;
using System.Web.Mvc;
using MvcFluentValidation.ModelValidators;

namespace MvcFluentValidation.Models
    public class Enums
        public enum ApplicationStatus
            Pending = 0,
            Submitted = 1,
            Disapproved = 2,
            Approved = 3

    public class FluentDataModel
        public int ValInt1 { get; set; }

        public int? ValInt2 { get; set; }

        public string ValString1 { get; set; }

        public string ValString2 { get; set; }

        public double ValDouble1 { get; set; }

        public double? ValDouble2 { get; set; }

        public DateTime ValDateTime1 { get; set; }

        public DateTime? ValDateTime2 { get; set; }

        public SelectList ApplicationStatus { get; set; }

        public int SelectedApplicationStatus { get; set; }

        public DateTime? ApplicationSubmitted { get; set; } 

Add the Provider to the Global.asax file App_Start() method


And the validation works (Note: the dependency validation is only on the server, not as good as a custom RequiredIf validator!):

Client validation

Server side validation:


One comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: