【问题标题】:FluentValidation and nested validatorFluentValidation 和嵌套验证器
【发布时间】:2019-04-21 21:20:32
【问题描述】:

我有一堂课:

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 验证器不起作用?

【问题讨论】:

标签: c# validation fluentvalidation


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2012-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-16
    • 1970-01-01
    • 2019-09-17
    • 2020-01-11
    • 1970-01-01
    相关资源
    最近更新 更多