Simple MVC Application using FluentValidation.MVC4

This is a simple example of MVC application using FluentValidation.MVC4.
http://fluentvalidation.codeplex.com/

Create a new web application MVC4.

Get the fluent validation using nuget:
NugetFluent

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)
            .NotNull();
            RuleFor(x => x.ValString2)
                .NotNull()
                .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
        }
    }

    [FluentValidation.Attributes.Validator(typeof(FluentDataModelValidator))]
    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

FluentValidationModelValidatorProvider.Configure();

And the validation works (Note: the dependency validation is only on the server, not as good as a custom RequiredIf validator!):
See https://damienbod.wordpress.com/2013/07/11/simple-mvc-application-using-standard-validation/

Client validation
FluentValidation1

Server side validation:
FluentValidation2

code: https://github.com/damienbod/MvcFluentValidation.git

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: