繁体   English   中英

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

[英]Can I use DataAnnotations to validate a collection property?

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

    public class MyModel
    {
        //...

        [Required]
        public List<string> Identifiers { get; set; }

        // ....
    }

我宁愿不创建一个新类只是为了包装字符串。

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

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));
    }
}

编辑:如果s为空,则base.IsValid(s)返回 true,因此如果字符串成员不能为空,请改用:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM