Oleg Sh
Oleg Sh

Reputation: 9013

FluentValidation and nested validator

I have a class:

public class ClientInfo
{
    public string LabAccount { get; set; }
    //....
}

and validator class:

public class ClientInfoFluentValidator : AbstractValidator<ClientInfo>
{
    public ClientInfoFluentValidator()
    {
        RuleFor(d => d.LabAccount)
            .NotEmpty()
            .WithMessage("LabAccount is required");

        RuleFor(d => d.LabAccount)
            .Length(8)
            .WithMessage("LabAccount is limited by 8 letters");
        //....
    }
}

then I have class, which has ClientInfo class as property:

public class Order
{
    public ClientInfo ClientInfo { get; set; }
    //....
}

and validator class:

public class OrderFluentValidator : AbstractValidator<Order>
{
    public OrderFluentValidator()
    {
        //...
        RuleFor(d => d.ClientInfo)
            .NotNull()
            .WithMessage("ClientInfo part is required");

        RuleFor(d => d.ClientInfo)
            .SetValidator(new ClientInfoFluentValidator());
    }
}

When I try to validate only ClientInfo it works:

    ClientInfoFluentValidator validator = new ClientInfoFluentValidator();
    [TestMethod]
    public void ClientInfoInvalidLabAccountLength()
    {
        ClientInfo model = new ClientInfo
        {
            LabAccount = "1234567"
            //....
        };

        validator.ShouldHaveValidationErrorFor(d => d.LabAccount, model);
        //....
    }

but when I try to validate Order class:

    OrderFluentValidator validator = new OrderFluentValidator();
    [TestMethod]
    public void OrderInfoValid()
    {
        Order model = new Order
        {
            ClientInfo = new ClientInfo
            {
                LabAccount = "1234567"
                //....
            },
            //....
        };

        validator.ShouldHaveValidationErrorFor(d => d.ClientInfo, model);
    }

It says, that model class is valid. Why so? why ClientInfo validator does not work?

Upvotes: 3

Views: 6439

Answers (1)

Greg Burghardt
Greg Burghardt

Reputation: 18783

You need to specify the exact property on the child view model that should have the error message. This appears to be a problem with the assertion, not your view models or validators:

validator.ShouldHaveValidationErrorFor(d => d.ClientInfo.LabAccount, model);

Upvotes: 1

Related Questions