Search code examples
c#validationmessagefluentvalidation

FluentValidation - How to customize the validation message in runtime


In this entity:

public class Foo
{
    public Guid Id { get; set; }
    public string Type { get; set; }
    public string Name { get; set; }
}

How can I customize the validation message in runtime using another property of entity or any other string obtained from the database?

The validation message for RuleFor(foo => foo.Name) would be:

var msg = "The foo with type '" + foo.Type + "' already exists in the database with name '" + nameInDataBase + "'!"

Solution

  • As I had a complex scenario, the solution that solved my problem was found here: Custom Validators.

    Here's the validator code:

    public class FooValidator : AbstractValidator<Foo>
    {
        public FooValidator()
        {
            Custom(foo =>
            {
                var repo = new Repository<Foo>();
                var otherFooFromDB = repo.GetByName(foo.Name);
    
                if (!otherFooFromDB.Equals(foo))
                {
                    return new ValidationFailure("Id", "The foo with ID'" + otherFooFromDB.Id + "' has the same name of this new item '" + foo.Id + " - " + foo.Name + "'.!");
                }
                else
                {
                    return null;
                }
            });
        }
    }
    

    With this solution when validation is ok just return null. But when there is a validation error return a instance of ValidationFailure and pass in her constructor the name of the validated property and the validation message.