列表参数的 FluentValidation
我们有一个现有的 API 端点,其签名如下(简化):
[HttpPost("api/v1/data")]
public DataSubmission SubmitData([FromBody] List<DataItem> items) {
...
}
public class DataItemValidator : AbstractValidator<DataItem> {
// RuleFor(...)
}
我们已经为 DataItem
定义了一个验证器,但我们不知道如何在各个列表项上注册验证。对于列表作为属性公开的常规输入模型,使用 RuleForEach(x => x.ListPropertyName).SetValidator(...)
很方便,但我们找不到一个设置当要验证的模型本身是一个列表时,我们可以验证项目。
我们尝试为此列表定义一个派生模型,并为其创建一个验证器,如下所示:
public class DataItemList : List<DataItem> {
}
public class DataItemListValidator : AbstractValidator<DataItemList> {
public DataItemListValidator(){
// How to set validator for items list??
}
}
我们是否以错误的方式处理此问题,或者是否有其他方法来处理这种情况?
编辑:我知道 FluentValidation 不适合验证参数(https://github.com/ FluentValidation/FluentValidation/issues/337),但我不确定这是否也适用,因为它似乎有点灰色区域
We have an existing API endpoint with a signature like the following (simplified):
[HttpPost("api/v1/data")]
public DataSubmission SubmitData([FromBody] List<DataItem> items) {
...
}
public class DataItemValidator : AbstractValidator<DataItem> {
// RuleFor(...)
}
We have defined a validator for the DataItem
but we cannot figure out how to register the validation on the individual list items. For regular input models where the list is exposed as a property, it is convenient to use RuleForEach(x => x.ListPropertyName).SetValidator(...)
but we fail to find a setup where we can validate the items when the model to validate is a list in itself.
We have attempted to define a derived model for this list and create a validator for it like this:
public class DataItemList : List<DataItem> {
}
public class DataItemListValidator : AbstractValidator<DataItemList> {
public DataItemListValidator(){
// How to set validator for items list??
}
}
Are we going about this the wrong way or are there other ways to handle this scenario?
EDIT: I am aware of FluentValidation not being suitable for validating parameters (https://github.com/FluentValidation/FluentValidation/issues/337) but I am not sure if this applies as well since it seems to be somewhat of a grey area
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
(在发布问题后不久找到答案)
我们可以使用派生模型和特定的 RuleForEach 语法来实现验证:
这里的关键是允许迭代元素的
(x => x)
本身。(Found an answer shortly after posting question)
We can achieve the validation using the derived model and a specific RuleForEach syntax:
The key here is the
(x => x)
that allows for iterating the element of itself.