HTML maxlength
Created By: chatGPT
maxlength is an HTML attribute that defines the maximum number of characters allowed in an
<input>
or <textarea>
element. It is particularly useful to ensure that user input does not exceed a certain length, which can help with data validation and database constraints. This attribute can be used with various input types, such as text, email, or number, but it does not apply to all input types. Here’s how to implement it in your HTML code.<form>
<label for="username">Username:</label>
<input type="text" id="username" name="username" maxlength="15" placeholder="Max 15 characters">
<label for="bio">Bio:</label>
<textarea id="bio" name="bio" maxlength="100" placeholder="Max 100 characters"></textarea>
<input type="submit" value="Submit">
</form>
In the example above, the maxlength attribute is set to 15 for the username input and 100 for the bio textarea. This means that users cannot enter more than these limits, enhancing user experience and data integrity.
<input type="text" maxlength="15">
<textarea maxlength="100"></textarea>
Additionally, while maxlength helps to restrict input length, it does not prevent users from submitting the form with invalid values if you are not validating on the server-side. Always remember to combine client-side restrictions with server-side validation for maximum security.
// Server-side validation example in JavaScript
if (username.length > 15) {
throw new Error("Username cannot exceed 15 characters");
}
if (bio.length > 100) {
throw new Error("Bio cannot exceed 100 characters");
}