英文:
Fluent validation does not validate fields of objects in an array
问题
我有以下的验证器。它在根级别的字段上按预期工作。但是,似乎对数组中的对象字段没有进行验证。
public class ReporterValidator : AbstractValidator<Reporter>
{
public ReporterValidator()
{
RuleFor(a => a.Name).Length(5, 10);
RuleForEach(a => a.Fields).ChildRules(a =>
{
a.RuleFor(b => b.Key).Length(4, 8);
a.RuleFor(b => b.Retention).InclusiveBetween(2, 7);
});
}
}
类声明如下:
public class Reporter
{
public string Name { get; set; } = default!;
public Field[] Fields { get; set; } = Array.Empty<Field>();
public class Field
{
public string Key { get set; } = default!;
public int Retention { get; set; } = default!;
}
}
我可能遗漏了什么?
我遵循的来源是这里。我理解的是,我不需要为存储在数组中的类型添加单独的验证器类,也不需要显式注册,只需要像下面这样:
services.AddScoped<IValidator<Reporter>, ReporterValidator>();
英文:
I have the following validator. It works as supposed to on the fields in the root level. However, it seems that there's no validation on the fields of the objects in the array.
public class ReporterValidator : AbstractValidator<Reporter>
{
public ReporterValidator()
{
RuleFor(a => a.Name).Length(5, 10);
RuleForEach(a => a.Fields).ChildRules(a =>
{
a.RuleFor(b => b.Key).Length(4, 8);
a.RuleFor(b => b.Retention).InclusiveBetween(2, 7);
});
}
}
The classes are declared as follows.
public class Reporter
{
public string Name { get; set; } = default!;
public Field[] Fields { get; set; } = Array.Empty<Field>();
public class Field
{
public string Key { get; set; } = default!;
public int Retention { get; set; } = default!;
}
}
What could I be missing?
The source I'm following is here. My understanding is that I don't need to add separate validator class for the type stored in the array nor, by extension, register that explicitly other than:
services.AddScoped<IValidator<Reporter>, ReporterValidator>();
答案1
得分: 1
不太喜欢回答自己的问题,但这一次我会这么做。
问题是调用注册验证功能(即AddFluentValidationAutoValidation()
)被移除了(在我的测试之间的时间间隔非常不合适)。
public static void Main(string[] args)
{
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
IServiceCollection services = builder.Services;
...
services.AddFluentValidationAutoValidation();
...
}
一旦上面示例中的最后一条语句存在,验证起作用了 - 对于根对象和数组对象都有效。正如预期的那样...
英文:
Not a big fan of answering my own question but I'll do it this time.
The issue was that the call to register the validation facility (i.e. AddFluentValidationAutoValidation()
) was removed (with a sorely poor timing between my tests).
public static void Main(string[] args)
{
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
IServiceCollection services = builder.Services;
...
services.AddFluentValidationAutoValidation();
...
}
Once the last statement in the sample above is present, the validation works - both for root objects and for array objects. As expected...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论