简体   繁体   English

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

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

I have a model for a WebAPI2 controller with a field that takes in a collection (List) of strings.我有一个 WebAPI2 控制器模型,该控制器带有一个接收字符串集合(列表)的字段。 Is there a way that I can specify DataAnnotations (eg [MaxLength]) for the strings to ensure, via validation, that none of the strings in the list is > 50 in length?有没有一种方法可以为字符串指定 DataAnnotations(例如 [MaxLength]),以通过验证确保列表中的所有字符串的长度都不大于 50?

    public class MyModel
    {
        //...

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

        // ....
    }

I'd rather not create a new class simply to wrap the string.我宁愿不创建一个新类只是为了包装字符串。

You can write your own validation attribute, eg as follows:您可以编写自己的验证属性,例如如下:

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

You will be able to place it directly over your property:您将能够将其直接放置在您的财产上:

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

I know this question is ages old, but for those that stumble upon it, here is my version of a custom attribute inspired by the accepted answer.我知道这个问题由来已久,但对于那些偶然发现它的人来说,这是我的自定义属性版本,其灵感来自已接受的答案。 It makes use of the StringLengthAttribute to do the heavy lifting.它利用 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));
    }
}

Edit: base.IsValid(s) returns true if s is null, so if the string members must not be null, use this instead:编辑:如果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.

相关问题 我可以使用DataAnnotations在.NET中自定义验证对象吗? - Can I use DataAnnotations to custom validate an object in .NET? 如果其他属性设置为true,如何使用mvc数据注释来验证属性值? - How to use mvc dataannotations to validate property value if other property is set to true? 为什么不能将DataAnnotations KeyAttribute用于复合键? - Why can't i use DataAnnotations KeyAttribute for composite keys? 为什么我不能将资源用作带有 DataAnnotations 的 ErrorMessage? - Why can't I use resources as ErrorMessage with DataAnnotations? 我可以在抽象基类属性中使用泛型集合吗? - Can I use a generic collection in an abstract base class property? 如何验证要添加到集合属性中的项目? - How do I validate an item that is being Added to property that is a collection? 我应该在哪里验证添加到我的实体的集合属性? - Where should I validate adding to my entity's collection property? 我可以在 DataAnnotations.StringLength 中使用数字以外的其他属性参数吗? - Can I use other attribute arguments than numbers in DataAnnotations.StringLength? 使用属性上的sum验证集合 - Validate collection using sum on a property 如何使用 DataAnnotations 检查属性是否仅匹配字符串数组 - How to use DataAnnotations to check a property only matches an array of string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM