简体   繁体   中英

FluentValidation on Collection in Non-Wrapper Class in C#

Every time I see FluentValidation upon a collection, there's a wrapper class around the list like below in A. The problem with the wrapper class is that the collection has to be assigned to a field name, but I want my request to look like: [{}, {}] rather than: {fooBars: [{},{}]} . The FooBar validator doesn't seem to know how to validate a List of FooBar on its own.

How can I ensure validation on a List of FooBar without assigning the list to a field in the request?

A. 
public async Task<IActionResult> PostFooBarsAsync(Foos request,
            CancellationToken cancellationToken = default(CancellationToken))

where

public class Foos{
  public List<FooBar> FooBars { get; set; } = new List<FooBar>();
}

and

 public class FoosValidator : AbstractValidator<Foos> {
   public FoosValidator() {
    RuleForEach(x => x.FooBars).SetValidator(new FooBarValidator());
  }
}

Vs.

B.
public async Task<IActionResult> PostFooBarAsync(List<FooBar> request,
            CancellationToken cancellationToken = 
default(CancellationToken))

with validator

public class FooBarValidator : AbstractValidator<FooBar>
{
    public FooBarValidator()
    {

        RuleFor(x => x.FooBarNumber)
            .GreaterThan(0)
            .WithMessage("Field must be greater than zero");
         }
}

and FooBarValidator is not called.

我最终遍历 List 请求中的每个项目,并在 Controller 方法中的 FooBarValidator 实例上调用 .Validate() 函数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM