我可以使用DataAnnotations来验证集合属性吗?

本文关键字:集合 属性 验证 可以使 DataAnnotations 我可以 | 更新日期: 2023-09-27 18:17:25

我有一个WebAPI2控制器模型,该控制器带有一个字段,该字段接受字符串集合(List)。是否有一种方法,我可以指定DataAnnotations(例如[MaxLength])的字符串,以确保,通过验证,在列表中的字符串都不是> 50的长度?

    public class MyModel
    {
        //...
        [Required]
        public List<string> Identifiers { get; set; }
        // ....
    }

我不想仅仅为了包装字符串而创建一个新类。

我可以使用DataAnnotations来验证集合属性吗?

您可以编写自己的验证属性,例如:

public class NoStringInListBiggerThanAttribute : ValidationAttribute
{
    private readonly int length;
    public NoStringInListBiggerThanAttribute(int length)
    {
        this.length = length;
    }
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var strings = value as IEnumerable<string>;
        if(strings == null)
            return ValidationResult.Success;
        var invalid = strings.Where(s => s.Length > length).ToArray();
        if(invalid.Length > 0)
            return new ValidationResult("The following strings exceed the value: " + string.Join(", ", invalid));
        return ValidationResult.Success;
    }
}

你可以把它直接放在你的属性上:

[Required, NoStringInListBiggerThan(50)]
public List<string> Identifiers {get; set;}

我知道这个问题很老了,但是对于那些偶然发现它的人,这里是我的自定义属性版本,灵感来自于公认的答案。它使用StringLengthAttribute来完成繁重的工作。

/// <summary>
///     Validation attribute to assert that the members of an IEnumerable&lt;string&gt; property, field, or parameter does not exceed a maximum length
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)]
public class EnumerableStringLengthAttribute : StringLengthAttribute
{
    /// <summary>
    ///     Constructor that accepts the maximum length of the string.
    /// </summary>
    /// <param name="maximumLength">The maximum length, inclusive.  It may not be negative.</param>
    public EnumerableStringLengthAttribute(int maximumLength) : base(maximumLength)
    {
    }
    
    /// <summary>
    ///     Override of <see cref="StringLengthAttribute.IsValid(object)" />
    /// </summary>
    /// <remarks>
    ///     This method returns <c>true</c> if the <paramref name="value" /> is null.
    ///     It is assumed the <see cref="RequiredAttribute" /> is used if the value may not be null.
    /// </remarks>
    /// <param name="value">The value to test.</param>
    /// <returns><c>true</c> if the value is null or the length of each member of the value is between the set minimum and maximum length</returns>
    /// <exception cref="InvalidOperationException"> is thrown if the current attribute is ill-formed.</exception>
    public override bool IsValid(object? value)
    {
        return value is null || ((IEnumerable<string>)value).All(s => base.IsValid(s));
    }
}

编辑:base.IsValid(s)返回true如果s为null,所以如果字符串成员不能为空,使用这个代替:

public override bool IsValid(object? value)
{
    return value is null || ((IEnumerable<string>)value).All(s => !string.IsNullOrEmpty(s) && base.IsValid(s));
}
相关文章: