C#流利验证

时间:2020-05-21 19:48:00

标签: c# fluentvalidation

我有以下流利的验证,正在部分工作。如果输入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"
            }
    }

1 个答案:

答案 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会引发异常。