FluentValidation v3: CustomizeValidatorAttribute

This is part 2 in a series about new features in FluentValidation v3.

FluentValidation supports integration with ASP.NET MVC’s validation infrastructure. This allows you to plug FluentValidation into MVC’s model-binding process so that complex types are validated when they are constructed from form/querystring parameters.

However, using this approach means that you don’t have access to the validator directly which means that you don’t have as much control over the validation processes compared to running the validator manually.

With FluentValidation v3 you can use the CustomizeValidatorAttribute to configure how the validator will be run. For example, if you want the validator to only run for a particular ruleset then you can specify that ruleset name by attributing the parameter that is going to be validated:

public ActionResult Save([CustomizeValidator(RuleSet="MyRuleset")] Customer cust) {
  // ...
}

This is the equivalent of specifying the ruleset if you were to pass a ruleset name to a validator:

var validator = new CustomerValidator();
var customer = new Customer();
var result = validator.Validate(customer, ruleSet: "MyRuleset");

The attribute can also be used to invoke validation for individual properties:

public ActionResult Save([CustomizeValidator(Properties="Surname,Forename")] Customer cust) {
  // ...
}

…which would be the equivalent of specifying properties in the call to validator.Validate:

var validator = new CustomerValidator();
var customer = new Customer();
var result = validator.Validate(customer, properties: new[] { "Surname", "Forename" });

There is one other feature of the CustomizeValidatorAttribute – you can specify an Interceptor. This will be the subject of my next post.

Written on February 4, 2011