Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET-MVC 2 DataAnnotations StringLength

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?

like image 789
griegs Avatar asked Mar 22 '10 02:03

griegs


2 Answers

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; }
like image 65
Jim Geurts Avatar answered Nov 15 '22 19:11

Jim Geurts


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; }
like image 7
Josiah Ruddell Avatar answered Nov 15 '22 18:11

Josiah Ruddell