gpt4 book ai didi

c# - 流利的验证 SetCollectionValidator

转载 作者:太空宇宙 更新时间:2023-11-03 18:24:46 25 4
gpt4 key购买 nike

亲爱的我正在尝试使用 SetCollectionValidator 验证对象列表并且列表计数可能有 0 个对象或更多对象所以验证返回错误直到列表没有这样的项目

public class SCRequest
{
public List<Attachment> Attachments { get; set; }
}

public class Attachment
{
public int AttachmentId { get; set; }
public string Name { get; set; }
public string FileType { get; set; }
public string FilePath { get; set; }
public string FileUrl { get; set; }
}

现在为了验证 ScRequest,我执行以下操作

public SCRequestValidator()
{
RuleFor(request => request.Attachments)
.SetCollectionValidator(new AttachmentValidator());
}

为了验证附件,我执行以下操作

public AttachmentValidator()
{
RuleFor(x => x.FileUrl)
.NotNull()
.WithMessage(ErrorMessage.B0001)
.NotEmpty()
.WithMessage("Not Allowed Empty");
}

当附件列表有 0 个对象时,我得到错误不是 Not Allowed Empty,我的问题是我只想在列表有值时验证它。

我该如何解决?

最佳答案

您可以使用 When() 将规则/验证器设置为仅在某些情况下被调用。在您的示例中,代码将类似于:

public SCRequestValidator()
{
When(request => request.Attachments.Any(), () =>
{
RuleFor(request => request.Attachments)
.SetCollectionValidator(new AttachmentValidator());
});
}

因此,如果没有附件,则不会设置 CollectionValidator。

关于c# - 流利的验证 SetCollectionValidator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37408461/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com