我有一堂课: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 回答
青春有我
TA贡献1784条经验 获得超8个赞
您需要在应该具有错误消息的子视图模型上指定确切的属性。这似乎是断言的问题,而不是您的视图模型或验证器:
validator.ShouldHaveValidationErrorFor(d => d.ClientInfo.LabAccount, model);
- 1 回答
- 0 关注
- 72 浏览
添加回答
举报
0/150
提交
取消