-1

I am working in VisualStudio with a Product object from a model. I am very unfamiliar with custom attributes. I would like to restrict a Product's name, for example, to 3 words maximum.

    [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; }
andres
  • 301
  • 6
  • 21
  • so create a custom attribute and do your custom validation. searching for "custom validation in MVC" should not be that hard. [here](http://stackoverflow.com/a/16100455/3010968) is an example – Selman Genç Feb 13 '15 at 19:16
  • There's no built-in attribute for this. Possibly because there's no standard definition of what "3 words" means. You're going to have to define the logic yourself in a custom validation attribute. – David Feb 13 '15 at 19:19

1 Answers1

2

You could easily limit to 3 words using a regular expression.

[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.")]

Do note that your definition of "word" might mean something else than this, though. So you may need to tweak the regular expression.

NightOwl888
  • 55,572
  • 24
  • 139
  • 212