C# 流利验证

C# Fluent-validations

我有以下流畅的验证,正在部分工作。如果我输入 3 个请求的值是有效的,但如果我输入 2 个值也是有效的。它应该不起作用,因为所有 3 个值都是强制性的。

 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"
            }
    }

这取决于您对验证器的期望。

默认情况下,如果你写

var results = validator.Validate(new TestData
{
    Entities = new List<string> { "", "" }
});

它不会抛出异常,但会抛出 return 结果,您可以稍后查看。

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