gpt4 book ai didi

c# - FluentValidation 和嵌套验证器

转载 作者:太空宇宙 更新时间:2023-11-03 12:04:24 25 4
gpt4 key购买 nike

我有一个类:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com