views:

43

answers:

3

What is the purpose and proper use of the max-length property on text fields?

The application I'm working on limits numeric fields to 6 characters... which doesn't work very well for entering millions of dollars... which is why I'm "fixing" it.

A: 

MaxLength Sets or receives the maximum number of characters that a user can enter into a Text control.

EDIT: You do this to prevent having to process something that you know is guaranteed to be wrong.

smoore
Yes it does. But why?
If the field is a given length, then you might not want to allow users to enter a value you know to be incorrect, like a product key. If the user notices that what they're typing has stopped appearing in the textbox, then they know they've typed something in wrong.
smoore
A: 

If you have a text field in your database that is set to 10 characters and the user enters 11 and you don't handle it properly, you cause an exception.

So, just set the maxlength to 10 and you won't have any problems like this.

Jack Marchetti
@Jack - What about numeric fields?
Well for numeric's you'll need to do other checking.
Jack Marchetti
@Jack - Yup. But how would you apply maxlength to numeric fields?
ohh, in webforms you can use things like range validators or comparison validators. or you could always do a tryparse on the input before it ever gets near your database.
Jack Marchetti
A: 

The Maximum length attribute of a text field and/or textarea effectively limits the user from entering data that is outside the bounds and constraints you have set for your database.

You can use this to make sure users enter in valid SKU numbers, blog titles, ISBN numbers, etc. It is a rudimentary form of data validation.

This doesn't always need to be tied to data validation though.

You could want to limit the length of a string that a user has entered for aesthetic reasons when displaying that data on a page in another location.

Mike Trpcic