首页 > 解决方案 > 将 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)]

这看起来不太好。

标签: c#

解决方案


要创建自定义数据注释验证器,请遵循以下准则:

  1. 您的类必须继承自 System.ComponentModel.DataAnnotations.ValidationAttribute 类。
  2. 覆盖 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; }
}

推荐阅读