我有一堂課:public class ClientInfo{ public string LabAccount { get; set; } //....}和驗(yàn)證器類: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; } //....}和驗(yàn)證器類:public class OrderFluentValidator : AbstractValidator<Order>{ public OrderFluentValidator() { //... RuleFor(d => d.ClientInfo) .NotNull() .WithMessage("ClientInfo part is required"); RuleFor(d => d.ClientInfo) .SetValidator(new ClientInfoFluentValidator()); }}當(dāng)我嘗試僅驗(yàn)證ClientInfo它時(shí): ClientInfoFluentValidator validator = new ClientInfoFluentValidator(); [TestMethod] public void ClientInfoInvalidLabAccountLength() { ClientInfo model = new ClientInfo { LabAccount = "1234567" //.... }; validator.ShouldHaveValidationErrorFor(d => d.LabAccount, model); //.... }但是當(dāng)我嘗試驗(yàn)證Order類時(shí): OrderFluentValidator validator = new OrderFluentValidator(); [TestMethod] public void OrderInfoValid() { Order model = new Order { ClientInfo = new ClientInfo { LabAccount = "1234567" //.... }, //.... }; validator.ShouldHaveValidationErrorFor(d => d.ClientInfo, model); }它說,那個(gè)model類是有效的。為什么這樣?為什么ClientInfo驗(yàn)證器不起作用?
1 回答

青春有我
TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超8個(gè)贊
您需要在應(yīng)該具有錯(cuò)誤消息的子視圖模型上指定確切的屬性。這似乎是斷言的問題,而不是您的視圖模型或驗(yàn)證器:
validator.ShouldHaveValidationErrorFor(d => d.ClientInfo.LabAccount, model);
- 1 回答
- 0 關(guān)注
- 97 瀏覽
添加回答
舉報(bào)
0/150
提交
取消