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

问题描述:

我试图找出是否有一种适当的方法可以通过DataAnnotations实现此目的:

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

有一个数组或字符串列表,其中元素的最大数量数组或列表有2个项目,每个字符串只能有255个字符长。这项工作会起作用:

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

我宁愿不必为了容纳字符串 Value 属性可将每个字符串限制为255个字符。

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

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

You can create your own validation attribute by inheriting from Validation Attribute like described here: How to: Customize Data Field Validation in the Data Model Using Custom Attributes