YouTip LogoYouTip

Prop Webcontrol Textbox Maxlength

## ASP.NET Web Control: TextBox MaxLength Property The `MaxLength` property is a key attribute of the ASP.NET Web Control `TextBox`. It allows developers to define or retrieve the maximum number of characters that a user can input into a text box. --- ## Definition and Usage The `MaxLength` property specifies the maximum character limit for a `TextBox` control. Once this limit is reached, the browser prevents the user from typing any additional characters. This property is highly useful for validating input lengths (such as zip codes, phone numbers, or database-constrained string fields) directly on the client side before the form is submitted. --- ## Syntax ```xml ``` ### Property Values | Attribute | Type | Description | | :--- | :--- | :--- | | **num** | `Integer` | Specifies the maximum number of characters allowed in the text box. The default value is `0`, which means there is no limit imposed by the control. | --- ## Code Example The following example demonstrates how to restrict the user input in an ASP.NET `TextBox` control to a maximum of 10 characters: ```xml
``` --- ## Important Considerations When working with the `MaxLength` property, keep the following technical behaviors in mind: 1. **TextMode Compatibility**: The `MaxLength` property is fully supported when the `TextMode` property of the `TextBox` is set to `SingleLine` or `Password`. However, depending on the .NET Framework version and target browser, it may not behave consistently or be enforced when `TextMode` is set to `MultiLine`. For multi-line text areas, you may need to use custom JavaScript or ASP.NET RegularExpressionValidators to enforce character limits. 2. **Client-Side vs. Server-Side Validation**: While `MaxLength` restricts user input in the browser (client-side), malicious users can bypass client-side restrictions. Always validate the length of the input string on the server side (e.g., using `tb1.Text.Length`) before saving data to a database. 3. **Byte Count vs. Character Count**: The `MaxLength` property limits the number of *characters*, not the number of *bytes*. If your database column limit is defined in bytes (which can vary for Unicode characters in UTF-8 or UTF-16), ensure your validation logic accounts for this difference.
← Prop Webcontrol Textbox ReadonProp Webcontrol Textbox Column β†’