简体   繁体   English

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

[英]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.

相关问题 如果我没有在字符串属性上指定StringLength或MaxLength会发生什么? - What happens if I don't specify StringLength or MaxLength on a string property? System.ComponentModel.DataAnnotations 属性无法识别。 无法使用 StringLength 属性验证空字符串 - System.ComponentModel.DataAnnotations attribute not recognized. Unable to use StringLength attibute to verify empty string EditorFor 和 StringLength 数据注释 - EditorFor and StringLength DataAnnotations 如何从DataAnnotations获取StringLength - How to get the StringLength from DataAnnotations 如何将字符串“brakemeup”转换为 char[stringlength] 数组? - How to convert string “brakemeup” in to char[stringlength] array? 如何使用MaxLength设计String类? - How to design a String class with MaxLength? C#如何使用DataAnnotations StringLength和SubString删除文本 - C# How to use DataAnnotations StringLength and SubString to remove text System.ComponentModel.DataAnnotations MaxLength未显示 - System.ComponentModel.DataAnnotations MaxLength not showing EF CodeFirst 设置默认字符串长度并用 DataAnnotations 覆盖? - EF CodeFirst set default string length and override with DataAnnotations? 如何使用 DataAnnotations 检查属性是否仅匹配字符串数组 - How to use DataAnnotations to check a property only matches an array of string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM