在 FluentValidation 中验证整数列表

rak*_*los 2 fluentvalidation

如何使用流畅的验证来验证整数列表?

我的模型有:

 public List<int> WindowGlassItems { get; set; }
Run Code Online (Sandbox Code Playgroud)

模型验证器有

RuleFor(x => x.WindowGlassItems).SetCollectionValidator(new WindowGlassItemsValidator());

  public class WindowGlassItemsValidator : AbstractValidator<int>
    {
        public WindowGlassItemsValidator()
        {
            RuleFor(x=>x).NotNull().NotEqual(0).WithMessage("GLASS REQ");
        }
    }
Run Code Online (Sandbox Code Playgroud)

我越来越:

无法为表达式 x => x 自动确定属性名称。请通过调用“WithName”指定自定义属性名称。

bpr*_*ard 5

您看到该错误是因为您的 RuleFor 方法期望指定一个属性。我一直无法让 CollectionValidators 像您一样使用原始类型。相反,我使用这样的自定义验证方法Must

我对这种方法的唯一问题是我无法避免在 2 个验证中重复错误消息。如果列表为空时不需要它,则可以在NotNull调用后将其省略。

    RuleFor(x => x.WindowGlassItems)
        //Stop on first failure to avoid exception in method with null value
        .Cascade(CascadeMode.StopOnFirstFailure)
        .NotNull().WithMessage("GLASS REQ")
        .Must(NotEqualZero).WithMessage("GLASS REQ");

    private bool NotEqualZero(List<int> ints)
    {
        return ints.All(i => i != 0);
    }
Run Code Online (Sandbox Code Playgroud)