FluentValidation和嵌套验证器

时间:2019-04-21 21:20:32

标签: c# validation fluentvalidation

我有一堂课

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

和验证器类:

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");
        //....
    }
}

然后我有一个类,该类具有ClientInfo类作为属性:

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

和验证器类:

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

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

当我尝试仅验证ClientInfo时,它会起作用:

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

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

但是当我尝试验证Order类时:

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

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

它说model类是有效的。为什么这样?为什么ClientInfo验证程序不起作用?

1 个答案:

答案 0 :(得分:1)

您需要在子视图模型上指定应该具有错误消息的确切属性。这似乎是断言的问题,而不是您的视图模型或验证器:

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