FluentValidation message for nested properties

Roman Koliada picture Roman Koliada · Oct 10, 2016 · Viewed 9.7k times · Source

I have a class with a complex property:

public class A
{
    public B Prop { get; set; }
}

public class B
{
    public int Id { get; set; }
}

I've added a validator:

public class AValidator : AbstractValidator<A>
{
    public AValidator()
    {
        RuleFor(x => x.A.Id)
            .NotEmpty()
            .WithMessage("Please ensure you have selected the A object");            
    }
}

But during client-side validation for A.Id I still have a default validation message: 'Id' must not be empty. How can I change it to my string from the validator?

Answer

Aleksey L. picture Aleksey L. · Oct 18, 2016

You can achieve this by using custom validator for nested object:

public class AValidator : AbstractValidator<A>
{
    public AValidator()
    {
        RuleFor(x => x.B).NotNull().SetValidator(new BValidator());
    }

    class BValidator : AbstractValidator<B>
    {
        public BValidator()
        {
            RuleFor(x => x.Id).NotEmpty().WithMessage("Please ensure you have selected the B object");
        }
    }
}

public class A
{
    public B B { get; set; }
}

public class B
{
    public int Id { get; set; }
}