c# - 将 DataAnnotation 中的 ValidationAttributes 应用于 IEnumerable 的所有元素
问题描述
我Microsoft.Extension.Options
在 ASP.NET Core 3.1 中使用,我想验证配置文件中的条目。
为此,我希望将 aRangeAttribute
应用于 a 的每个元素IEnumerable
。
class MyConfiguration
{
[ApplyToItems]
[Range(1, 10)]
publlic IList<int> MyConfigValues { get; set; }
}
或类似的东西。方法怎么写ApplyToItems
?
据我所知,在验证ValidationAttributes
可能的情况下,无法检索另一个ApplyToItems
。
或者我可以想象这样的事情:
[Apply(Range(1, 10)]
public List<int> MyConfigValues { get; set; }
但这甚至是有效的语法吗?我将如何编写一个像 Apply 这样的属性,它将其他属性作为参数而不依赖于类似的东西
[Apply(new RangeAttribute(1, 10)]
这看起来不太好。
解决方案
要创建自定义数据注释验证器,请遵循以下准则:
- 您的类必须继承自 System.ComponentModel.DataAnnotations.ValidationAttribute 类。
- 覆盖 bool IsValid(object value) 方法并在其中实现验证逻辑。
而已。
(来自 如何创建自定义数据注释验证器)
所以在你的情况下,它可能是这样的:
public class ApplyRangeAttribute : ValidationAttribute
{
public int Minimum { get; set; }
public int Maximum { get; set; }
public ApplyRangeAttribute()
{
this.Minimum = 0;
this.Maximum = int.MaxValue;
}
public override bool IsValid(object value)
{
if (value is IList<int> list)
{
if (list.Any(i => i < Minimum || i > Maximum))
{
return false;
}
return true;
}
return false;
}
}
编辑
以下是您将如何使用它:
class MyConfiguration
{
[ApplyRange(Minimum = 1, Maximum = 10)]
public IList<int> MyConfigValues { get; set; }
}
推荐阅读
- python - 在 Python 中使用 alibi 包时,模块“pandas”没有属性“DataFrame”
- java - IntelliJ IDEA 无法识别 JavaFX 库
- stripe-payments - 是否可以使用 Stripe Connect 实现国际购物车?
- c - 如何解决 C 中的动态内存分配问题?
- javascript - 如何在 html 画布上显示范围滑块值
- embedded - 用stm32设计移位寄存器的最佳方法是什么
- angular - Angular 6 - 更新数组内的深层对象
- java - 值没有在 try 块下初始化?
- coq - 如何证明陈述是错误的
- php - 用php检查一个键在多维数组中是否有值