What is the maxlength attribute in HTML?

While developing web applications using HTML, we usually need to create forms. These can either be for user registration, feedback, or anything else.

We use input elements in HTML to take input from the user. Sometimes, we may want to restrict the length of the input by the user.

For example, let’s take a user’s userid as input. We can limit it to some specific length like 10. The user can now only enter 10 characters.

We can do this using the maxlength attribute on input elements in HTML.

We can use the following syntax for this:

<input maxlength="number" />

Here, number limits the number of characters that the user can enter.

Let’s take an example to understand it better.

Example

In the following example, we take User ID as input. Here, the user can enter only 10 characters because we give the maxlength attribute to the input element as 10.

Code

<html>
<head>
</head>
<body>
<div id="content">
<form>
<label for="userid">User ID:</label>
<!-- provide maxlength attribute -->
<input id="userid" type="text" maxlength="10" >
</form>
</div>
</body>
</html>

Output

Enter the user id in the input box below:

New on Educative
Learn any Language for FREE all September 🎉
For the entire month of September, get unlimited access to our entire catalog of beginner coding resources.
🎁 G i v e a w a y
30 Days of Code
Complete Educative’s daily coding challenge every day in September, and win exciting Prizes.

Free Resources