StringLength Validation in MVC

You’ve forced the customer to enter his name, but what happens if he enters a name of enormous length? Wikipedia says the longest name ever used belonged to a German typesetter who lived in Philadelphia. His full name is more than 500 characters long. Although the .NET string type can store (in theory) gigabytes of Unicode characters, the MVC Music Store database schema sets the maximum length for a name at 160 characters. If you try to insert a larger name into the database, you’ll have an exception on your hands. The StringLength attribute can ensure the string value provided by the customer will fit in the database:

[Required]
[StringLength(160)]
public string FirstName { get; set; }
[Required]
[StringLength(160)]
public string LastName { get; set; }

Notice how you can stack multiple validation attributes on a single property. With the attribute in place, if a customer enters too many characters, he’ll see the default error message shown below the LastName field in Figure.

MinimumLength is an optional, named parameter you can use to specify the minimum length for a string. The following code requires the FirstName property to contain a string with three or more characters (and less than or equal to 160 characters) to pass validation:

[Required]
[StringLength(160, MinimumLength=3)]
public string FirstName { get; set; }
Tagged . Bookmark the permalink.

Leave a Reply