3

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?

Oleg Sh
  • 8,496
  • 17
  • 89
  • 159
  • I ran into this too. It appears that calling "Validate" only validates that exact view model, not any of its child models. I haven't found a way to validate a hierarchy of view models in a single call to "Validate". – Greg Burghardt May 06 '19 at 12:18
  • Similar question: [Child Model Validation using Parent Model Values. Fluent Validation. MVC4](https://stackoverflow.com/q/18720105/3092298). – Greg Burghardt May 06 '19 at 12:20

1 Answers1

1

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);
Greg Burghardt
  • 17,900
  • 9
  • 49
  • 92