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

时间:2015-02-13 19:11:14

标签: c# asp.net-mvc object custom-attributes

我在Visual Studio中使用模型中的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; }

1 个答案:

答案 0 :(得分:2)

您可以使用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.")]

请注意,您对“单词”的定义可能意味着除此之外的其他内容。所以你可能需要调整正则表达式。