String[] 或 List<string> 的 DataAnnotations MaxLength 和 StringLength?

GCy*_*ala 6 c# data-annotations

我想弄清楚是否有适当的方法可以使用 DataAnnotations 实现这一点:

有一个数组或字符串列表,其中数组或列表中的最大元素数为 2 个项目,并且每个字符串可能只有 255 个字符长。这是否有效:

[MaxLength(2)]
[StringLength(255)]
public string[] StreetAddress { get; set; }
Run Code Online (Sandbox Code Playgroud)

我宁愿不必创建一个新类来保存一个字符串Value属性来将每个字符串限制为 255 个字符。

mus*_*ium 7

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


Sas*_*san 6

这是字符串列表的自定义属性:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)