使用 FluentValidation,获取错误元素的索引

问题描述 投票:0回答:1

使用 FluentValidation,我试图获取列表中无效元素的索引,但我只从 RuleFor 中得到错误。

RuleForEach(m => m.Attendees)
  .OverrideIndexer((_, _, element, _) => $"<{element}>")
  .ChildRules(a =>
  {
    a.RuleFor(at => at.Email).NotNull().EmailAddress();
  })
  .OverridePropertyName("Attendees")
  .WithMessage("At least 1 attendee is invalid.");

如何实现这一目标?

c# fluentvalidation
1个回答
0
投票

您可以在

ChildRules
块内自定义验证。

RuleForEach(m => m.Attendees)
    .ChildRules(a =>
    {
        a.RuleFor((model, element, context) =>
        {
            var index = ((List<Attendee>)context.ParentContext.InstanceToValidate).IndexOf(element);
            // You can now use the 'index' variable as needed
            return element.Email != null && element.Email.Contains("example");
        }).WithMessage("Invalid email for attendee at index {Index}");
    })
    .OverridePropertyName("Attendees")
    .WithMessage("At least 1 attendee is invalid.");

根据您的特定验证标准的需要调整 RuleFor 内的逻辑。

注意:这假设

Attendees
List<Attendee>
。如果您的收藏属于不同类型,请相应地调整演员阵容。

© www.soinside.com 2019 - 2024. All rights reserved.