ASP.NET MVC 5 Conditional Validation

This is something that I find really useful, and I’m glad that I found an elegant way of doing it. You can easily want to use the same ViewModel on two different actions of your controller and have different validations for each of them.

The Test Project

To help illustrate the issue and the solution, let’s describe a simple scenario for user management. We will have a controller that adds and edits users. I will abstract the business layer so we can focus only on the user interface validation.

Note that we don’t have any validation in our ViewModel, we will add them in a moment.

Installing Fluent Validation

What we will be using for validation is a library called FluentValidation. It is an attractive solution for validation in the .NET environment. To use it, the first thing that we need to do is install it via NuGet.

Install-Package FluentValidation.MVC5

The next step is to initialize the FluentValidation library during the application start using the Configure method. To do that, just add the following line to your Application_Start method.


If you are using Unity for Dependency Inject, also consider adding the following line in your registration method.

container.RegisterType<RuleSetForClientSideMessagesAttribute, RuleSetForClientSideMessagesAttribute>(new InjectionConstructor(typeof(string)));

Adding Validation

Now that we have the FluentValidation library up and running in our ASP.NET MVC 5 project let’s add validation to our ViewModel class. The way we will be doing this is by creating a validation class that we will be referencing from our ViewModel.

The RuleSet is one of the coolest things that FluentValidation has to offer, and what makes it so flexible. We will be using those rules with the controller in the next section. Now, we can decorate our model class with the Validator attribute.

The only thing new here is line 7, where we define which validator we will be using for this ViewModel class.

Setup the Conditional Validation

Now is when the magic really happens. We can specify in our action methods, which RuleSets we want to use for each action. We can use the RuleSetForClientSideMessages attribute for the HttpGet methods and CustomizeValidator for our model binding during Post events. And that is all we really need to do.


And really, that is all you need to do. No doubts on why this library is so popular. This approach is also beneficial if you want to do validation that requires business logic, for example: check the database to see if the email already exists:

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 )

Google+ photo

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

Connecting to %s