c# - FluentValidation 和嵌套验证器

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

最佳答案

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

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

关于c# - FluentValidation 和嵌套验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55786849/

相关文章:

forms - 如何验证至少应选中一个复选框?

c# - 如何在 View 上显示流利验证错误消息

c# - 如何将调试器附加到脚本

c# - Web API 自定义身份验证过滤器

c# - 在服务器端生成的 Excel 中获取 System.Runtime.InteropServices.COMException 错误

c# - 我应该在 FluentValidation 中为 Collection 创建一个新类型吗?

c# - FluentValidation 规则链接不会在第一次失败时停止

c# - 需要将科学值(value)转化为文本

javascript - 表单验证字段

java - 后台线程中的 Vaadin 表单验证?