30

Can I use the MVC 2 DataAnnotations to specify a minimum length for a string field?

Has anyone done this or have they created custom attributes and if so do you mind sharing the source?

skaffman
  • 398,947
  • 96
  • 818
  • 769
griegs
  • 22,624
  • 33
  • 128
  • 205

2 Answers2

73

If you're using asp.net 4.0, you can use the StringLength attribute to specify a minimum length.

Eg:

[StringLength(50, MinimumLength=1)]
public string MyText { get; set; }
Jim Geurts
  • 20,189
  • 23
  • 95
  • 116
  • 2
    No we're not using 4.0 just yet and the way things happen here it won't be for a long time yet. :) – griegs Mar 22 '10 at 23:07
  • FYI.. If you "under-post" (meaning you don't post a form field called "MyText"), the StringLength validation on that property will be ignored. [Here's an article](http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html) explaining this scenario using a similar attribute (RequiredAttribute). – tbehunin Mar 12 '12 at 21:00
7

Use a regular expression attribute. These are interpreted on the client side as well.

[RegularExpression(Regexes.MinStringLength)]
public string MyText { get; set; }

Where Regexes.MinStringLength is a static regular expression class. Inline would look like this:

[RegularExpression(@"^.{5,10}$")] // valid five to ten characters
public string MyText { get; set; }
Josiah Ruddell
  • 29,697
  • 8
  • 65
  • 67
  • Regexes.MinStringLength seems to be home grown, perhaps you could put in an example that works without need for other definitions? Maybe [RegularExpression(".{1}")], changing 1 for whatever min length you want. – Tim Abell Feb 23 '12 at 16:37
  • Sorry, that should read [RegularExpression(".{1,}")] - ref http://msdn.microsoft.com/en-us/library/az24scfc.aspx – Tim Abell Feb 23 '12 at 16:52