创建一个自定义属性,将属性限制为 n 个字符串

Create a custom attribute that restricts attribute to n number of strings

我在 VisualStudio 中使用来自模型的 Product 对象。我对自定义属性非常陌生。例如,我想限制产品名称最多 3 个字。

    [Required (ErrorMessage="Product name is required.")]
    [Display(Name = "Product Name")]
    [StringLength(30, ErrorMessage = "The {0} must be between {2} and {1} characters.", MinimumLength = 5)]
    [ExcludeChar("/.,!@#$%", ErrorMessage = "Name contains invalid character.")]

    // Custom annotation.

    public object ProductName { get; set; }

您可以使用 regular expression.

轻松限制为 3 个字
[RegularExpression(@"(?:\b\w+\b[\s\r\n]*){0,3}")] // Limits to 3 words
[Required (ErrorMessage="Product name is required.")]
[Display(Name = "Product Name")]
[StringLength(30, ErrorMessage = "The {0} must be between {2} and {1} characters.", MinimumLength = 5)]
[ExcludeChar("/.,!@#$%", ErrorMessage = "Name contains invalid character.")]

请注意,您对 "word" 的定义可能与此不同。所以你可能需要调整正则表达式。