Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FluentValidation message for nested properties

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?

like image 944
Roman Koliada Avatar asked Oct 10 '16 09:10

Roman Koliada


3 Answers

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; }
}
like image 145
Aleksey L. Avatar answered Oct 02 '22 14:10

Aleksey L.


There is an alternative option here. When configuring FluentValidation in your Startup class you can set the following configuration.ImplicitlyValidateChildProperties = true;

So the full code might look something like this

services
    .AddMvc()
    .AddFluentValidation(configuration =>
        {
            ...
            configuration.ImplicitlyValidateChildProperties = true;
            ...
        })

So you would still have two validators one for class A and one for class B, then class B would be validated.

The documentation states:

Whether or not child properties should be implicitly validated if a matching validator can be found. By default this is false, and you should wire up child validators using SetValidator.

So setting this to true implies that child properties will be validated.

like image 39
Steven Yates Avatar answered Oct 02 '22 16:10

Steven Yates


Pretty old question but for future generations - you can either use a child validator or define child rules inline as described in the official documentation: https://fluentvalidation.net/start#complex-properties

like image 20
t138 Avatar answered Oct 02 '22 14:10

t138