我有以下流利的验证,正在部分工作。如果输入3,则要求的值也有效,但是如果输入2,则要求的值也有效。应该不起作用,因为这三个值都是强制性的。
RuleFor(x => x.Entities).Must(list => list.Count == 3)
.WithMessage("The Entities list must contain 3 items and for AmendmentParties the RelationType must be CurrentName, ChangeAddName and AuthorizingPartyName ");
RuleForEach(x => x.Entities).ChildRules(x =>
{
x.RuleFor(x => x.RelationType).Equals(EntityAmendmentRelation.CurrentName)
.Equals(EntityAmendmentRelation.ChangeAddName)
.Equals(EntityAmendmentRelation.AuthorizingPartyName);
});
请求如下:目标是实体列表必须包含3个项目,并且在每个项目中,RelationType属性必须不同。
"entities": [
{
"ObjectType": "SecuredParty",
"reqSearchID": "NoSearch",
"RelationType": "CurrentName",
"altCapacity": "NoAltCapacity",
"OrganizationName": "Secured Party",
"Address": {
"StreetAddress": "12345 Main Street",
"City": "Sacramento",
"State": "CA",
"PostalCode": "95811",
"Country": "USA"
}
},
{
"ObjectType": "SecuredParty",
"reqSearchID": "NoSearch",
"RelationType": "ChangeAddName",
"altCapacity": "NoAltCapacity",
"OrganizationName": "Secured Party",
"Address": {
"StreetAddress": "12345 Main Street",
"City": "Sacramento",
"State": "CA",
"PostalCode": "95811",
"Country": "USA"
}
},
{
"ObjectType": "SecuredParty",
"reqSearchID": "NoSearch",
"RelationType": "AuthorizingPartyName",
"altCapacity": "NoAltCapacity",
"OrganizationName": "Secured Party",
"Address": {
"StreetAddress": "12345 Main Street",
"City": "Sacramento",
"State": "CA",
"PostalCode": "95811",
"Country": "USA"
}
}
答案 0 :(得分:0)
这取决于您希望验证者执行的操作。
默认情况下,如果您编写
var results = validator.Validate(new TestData
{
Entities = new List<string> { "", "" }
});
它不会引发异常,但是会返回结果,您以后可以检查。
bool success = results.IsValid;
如果需要它引发异常,请按以下方式使用它:
validator.ValidateAndThrow(new TestData
{
Entities = new List<string> { "", "" }
});
因此,对我来说,两种方法的验证均适用于以下配置
public class TestDataValidator : AbstractValidator<TestData>
{
public TestDataValidator()
{
RuleFor(x => x.Entities).Must(list => list.Count == 3)
.WithMessage("The Entities list must contain 3 items and for AmendmentParties the RelationType must be CurrentName, ChangeAddName and AuthorizingPartyName ");
}
}
使用第一种方法result.IsValid
是错误的;使用ValidateAndThrow
会引发异常。