![](/img/trans.png)
[英]What happens if I don't specify StringLength or MaxLength on a string property?
[英]DataAnnotations MaxLength and StringLength for string[] or List<string>?
我想弄清楚是否有适当的方法可以使用 DataAnnotations 实现这一点:
有一个数组或字符串列表,其中数组或列表中的最大元素数为 2 个项目,并且每个字符串可能只有 255 个字符长。 这是否有效:
[MaxLength(2)]
[StringLength(255)]
public string[] StreetAddress { get; set; }
我宁愿不必创建一个新类来保存一个字符串Value
属性来将每个字符串限制为 255 个字符。
您可以通过继承 Validation Attribute 来创建自己的验证属性,如下所述: 如何:使用自定义属性自定义数据模型中的数据字段验证
这是字符串列表的自定义属性:
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.