简体   繁体   中英

DataAnnotations MaxLength and StringLength for string[] or List<string>?

I am trying to figure out if there is a proper way to achieve this with DataAnnotations:

Have an array or List of strings where the maximum number of elements in the array or List is 2 items and where each string may only be, say 255 characters long. Will this work:

[MaxLength(2)]
[StringLength(255)]
public string[] StreetAddress { get; set; }

I would rather not have to make a new class just to hold a string Value property to constrain each string to 255 characters.

您可以通过继承 Validation Attribute 来创建自己的验证属性,如下所述: 如何:使用自定义属性自定义数据模型中的数据字段验证

This is a custom attribute for list of strings:

public class StringLengthListAttribute : StringLengthAttribute
{
    public StringLengthListAttribute(int maximumLength)
        : base(maximumLength) { }

    public override bool IsValid(object value)
    {
        if (value is not List<string>)
            return false;

        foreach (var str in value as List<string>)
        {
            if (str.Length > MaximumLength || str.Length < MinimumLength)
                return false;
        }

        return true;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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