0
0
HtmlConceptBeginner · 3 min read

Minlength and Maxlength in HTML: What They Are and How to Use

In HTML, minlength and maxlength are attributes used on input fields to set the minimum and maximum number of characters a user can enter. minlength ensures the input is not too short, while maxlength limits how long the input can be.
⚙️

How It Works

Think of minlength and maxlength as rules for how much text someone can type into a box. minlength is like saying, "You must write at least this many letters," so the input isn’t too short. maxlength is like a fence that stops you from typing too much.

When you add these attributes to an input box, the browser checks what the user types. If the text is shorter than minlength or longer than maxlength, the browser can show a message or prevent the form from being sent. This helps keep data clean and useful.

💻

Example

This example shows a text box where you must type between 3 and 10 characters. Try typing less or more to see how the browser reacts.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Minlength and Maxlength Example</title>
</head>
<body>
  <form>
    <label for="username">Username (3-10 characters):</label><br>
    <input type="text" id="username" name="username" minlength="3" maxlength="10" required>
    <br><br>
    <button type="submit">Submit</button>
  </form>
</body>
</html>
Output
A form with a text input labeled 'Username (3-10 characters):' and a submit button. The input only accepts between 3 and 10 characters.
🎯

When to Use

Use minlength and maxlength when you want to control how much text users can enter. For example, usernames often need a minimum length to be meaningful and a maximum length to fit in the design.

Other cases include passwords, phone numbers, or codes where length matters. These attributes help catch mistakes early, so users fix input before sending the form.

Key Points

  • minlength sets the smallest number of characters allowed.
  • maxlength sets the largest number of characters allowed.
  • Both work on text-based inputs like text, password, and email.
  • Browsers show built-in messages if input doesn’t meet these rules.
  • They improve user experience by guiding input length.

Key Takeaways

minlength and maxlength control input length in HTML forms.
They help ensure users enter data that fits your requirements.
Browsers enforce these rules and show messages if input is too short or too long.
Use them to improve form data quality and user experience.
They work on text inputs like username, password, and email fields.