[英]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:我想弄清楚是否有适当的方法可以使用 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.有一个数组或字符串列表,其中数组或列表中的最大元素数为 2 个项目,并且每个字符串可能只有 255 个字符长。 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.我宁愿不必创建一个新类来保存一个字符串
Value
属性来将每个字符串限制为 255 个字符。
您可以通过继承 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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.