亲爱的,我正在尝试使用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 Not Allowed Empty,我的问题是我只想在列表有值的时候验证它。
我怎么才能修复它呢?
发布于 2016-05-24 22:44:10
您可以通过使用When()将规则/验证器设置为仅在特定场景下调用。在您的示例中,代码将类似于:
public SCRequestValidator()
{
When(request => request.Attachments.Any(), () =>
{
RuleFor(request => request.Attachments)
.SetCollectionValidator(new AttachmentValidator());
});
}因此,如果没有附件,则不会设置CollectionValidator。
https://stackoverflow.com/questions/37408461
复制相似问题