I have the following class
public class ValidProjectHeader : AbstractValidator
{
public ValidProjectHeader()
{
Fluent validation 10+ onwards.
using FluentValidation;
var validationResult = await
validator.ValidateAsync(account,options=>options("nameOfRuleSet"));
I have found one way to do it by adding a second validator.Validate
to the CallValidation(string ruleSet)
method it is as follows
public virtual bool CallValidation(string ruleSet)
{
Errors = new List<ValidationFailure>();
ValidatorAttribute val = this.GetType().GetCustomAttributes(typeof(ValidatorAttribute), true)[0] as ValidatorAttribute;
IValidator validator = Activator.CreateInstance(val.ValidatorType) as IValidator;
FluentValidation.Results.ValidationResult result = validator.Validate(new FluentValidation.ValidationContext(this, new PropertyChain(), new RulesetValidatorSelector(ruleSet)));
FluentValidation.Results.ValidationResult resultCommon = validator.Validate(this);
IsValid = (result.IsValid && resultCommon.IsValid);
Errors = result.Errors.Union(resultCommon.Errors).ToList();
return IsValid;
}
In your Validator class create a method, that includes all "common" rules that need to be applied at all times. Now you can call this method
Example
public class MyEntityValidator : AbstractValidator<MyEntity>
{
public MyEntityValidator()
{
RuleSet("Create", () =>
{
RuleFor(x => x.Email).EmailAddress();
ExecuteCommonRules();
});
ExecuteCommonRules();
}
/// <summary>
/// Rules that should be applied at all times
/// </summary>
private void ExecuteCommonRules()
{
RuleFor(x => x.Name).NotEmpty();
RuleFor(x => x.City).NotEmpty();
}
}
You define the RuleSet for an action in your controller
[HttpPost]
public ActionResult Create([CustomizeValidator(RuleSet = "Create")] MyEntity model)
This will insure that requests to action Create will be validated with the RuleSet Create. All other action will use the call to ExecuteCommonRules in controller.
I just tried below and it works
[CustomizeValidator(RuleSet = "default, Create")
Instead you could do this:
using FluentValidation;
...
FluentValidation.Results.ValidationResult resultCommon =
validator.Validate(parameter, ruleSet: "default, Insert");
The using
directive is required to bring the Validate()
extension method from DefaultValidatorExtensions
into scope, which has the ruleSet
property. Otherwise you will only have the Validate()
method available from inheriting AbstractValidator<T>
, which doesn't have a ruleSet
argument.