The HTML maxlength attribute
The HTML maxlength attribute limits how many characters a user can type into a text field. Add it to an <input> or <textarea>, as in maxlength="280", and the browser stops accepting input at that length. It has no effect on type="number".
Overview
The HTML maxlength attribute sets the maximum number of characters a user can enter in a text field. Browsers enforce it while the user types, so the field simply stops accepting input at the limit. It belongs on <textarea> and on text, search, url, tel, email and password inputs.
The count uses UTF-16 code units, the unit behind JavaScript's string length. A line break in a textarea counts as one character, and MDN's compatibility data notes that Safari counted it as two before version 17. In our Chrome test, a pasted string was cut off at the limit as well, with no warning that the rest was dropped.
Two situations slip past the limit. A value set from JavaScript may be longer than maxlength without being marked invalid, because the check only covers user edits. Number inputs ignore the attribute completely, so a number field needs max instead.
The width of a field is a separate matter. Use size on an input or cols on a textarea to change how wide it looks, since neither of those limits the text and maxlength doesn't change the width.
Syntax
<label for="bio">Bio</label>
<textarea id="bio" name="bio" maxlength="160" rows="3"></textarea>
Values
| Value |
|---|
| A non-negative integer. |
Example
<label for="bio">Short bio</label><br>
<textarea id="bio" maxlength="40" rows="3" cols="30" aria-describedby="note"></textarea>
<p id="note"><span id="left">40</span> characters left</p>
<script>
document.getElementById('bio').addEventListener('input', function () {
document.getElementById('left').textContent = 40 - this.value.length;
});
</script>
Best practices
- Show the limit before users reach it. A remaining-characters counter tied to the field with aria-describedby works well.
- Match
maxlengthto the real limit of the database column or API, so accepted text is never cut short later. - Keep any
valueattribute within the limit. The HTML standard requires the initial value to be no longer thanmaxlength. - Use
max, notmaxlength, ontype="number"fields. - Validate the length again on the server, since scripts and direct requests can exceed it.
Accessibility
Tell people about the limit before they reach it. Put it in the label or in a hint linked with aria-describedby. If you turn a counter into a live region, use aria-live="polite", since MDN warns that assertive updates interrupt the screen reader and can be disruptive.
Frequently asked questions
How does the maxlength attribute work in HTML?
Why does maxlength not work on a number input?
type=text with a pattern when you need a fixed number of digits.






















