C# FluentValidation: Custom Validators with Dynamic Error Messages

Published on
1 mins read
--- views

Project link: [FluentValidation Custom Validators]

Useful article if you want to customize your validation (for example, bind parameters to your error message): [link]

Here is an example of a custom validator with error messages that use parameter bindings (thanks to user danludwig), from this StackOverflow post: [link]

public class IsProcessFileValid : PropertyValidator
{
    public IsProcessFileValid(): base({ValidationMessage}) {}

    protected override IsValid(PropertyValidatorContext context)
    {
        if (!IsProcessFileValid1(context))
            context.MessageFormatter.AppendArgument(ValidationMessage,
                Custom validation message #1);

        if (!IsProcessFileValid2(context))
            context.MessageFormatter.AppendArgument(ValidationMessage,
                Custom validation message #2);

        // ...etc

        return true;
    }

    private bool IsProcessFileValid1(PropertyValidatorContext context)
    {
        // logic
        return false;
    }

    private bool IsProcessFileValid2(PropertyValidatorContext context)
    {
        // logic
        return false;
    }

    // ...etc
}
public static class IsProcessFileValidExtensions
{
    public static IRuleBuilderOptions<T, object> MustBeValidProcessFile<T>
        (this IRuleBuilder<T, object> ruleBuilder)
    {
        return ruleBuilder.SetValidator(new IsProcessFileValid());
    }
}
public CreateProcessValidator()
{
    RuleFor(x => x.ProcessFile).MustBeValidProcessFile();
}