Open In App

How to Set Character Limits in HTML Input Fields?

Last Updated : 11 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

It’s often necessary to restrict the number of characters a user can input. This ensures data consistency and prevents users from entering values that are too long or too short. In this article, we will learn how to set the minimum and maximum number of characters allowed in an HTML input field.

To set the minimum character limit in the input field, we use <input> minlength attribute. This attribute is used to specify the minimum number of characters entered into the <input> element.

Syntax: 

<input maxlength="number1">
<input minlength="number2"> 

How to Set Character Limits in HTML Input Fields

HTML provides built-in attributes for specifying the minimum and maximum character limits for input fields:

  • maxlength Attribute: Sets the maximum number of characters allowed.
  • minlength Attribute: Sets the minimum number of characters required.

Example 1: Setting a Maximum Character Limit

In this example, we will create an input field with a maximum character limit of 12.

HTML
<!DOCTYPE html>
<html>

<head>
    <style>
        body {
            text-align: center;
        }
        h1 {
            color: green;
        }
    </style>
</head>
<body>
    <h1>GeeksforGeeks</h1>
    <h3>
        How to specify the maximum number
        of characters <br>allowed in an
        input field in HTML?
    </h3>
    <form action="#">
        Username:
        <input type="text" 
               name="username" 
               maxlength="12">
          <br><br>
        Password:
        <input type="password" 
               name="password" 
               maxlength="10">
          <br><br>
        <input type="submit" 
               value="Submit">
    </form>
</body>

</html>

Output: 

frt

Example 2: Setting Both Minimum and Maximum Character Limits

In this example, we will set a minimum character limit of 12 and a maximum character limit of 20 for an input field.

HTML
<!DOCTYPE html>
<html>
<head>
    <style>
        body {
            text-align: center;
        }
        h1 {
            color: green;
        }
    </style>
</head>
<body>
    <h1>
          GeeksforGeeks
      </h1>
    <h3>
        How to specify the maximum &amp; minimum number
        of characters <br>allowed in an
        input field in HTML?
    </h3>
    <form action="#">
        Username:
        <input type="text" 
               name="username"
               minlength="12" 
               maxlength="20"><br><br>
        Password:
        <input type="password" 
               name="password" 
               minlength="10" 
               maxlength="20">
          <br><br>
        <input type="submit" value="Submit">
    </form>
</body>

</html>

Output:



Next Article

Similar Reads