HTML minlength Attribute
Description
The minlength
attribute in HTML is used to specify the minimum number of characters a <input>
or <textarea>
element must have before the form can be submitted. This attribute applies only when the type
attribute of the <input>
element is set to text
, email
, search
, password
, tel
, or url
. It's particularly useful for ensuring that inputs meet certain criteria for strength or completeness, such as a minimum password length or a sufficiently long text response.
For example, if you're creating a form that requires a user to enter a password, you might set the minlength
attribute on the password field to ensure that the user's password is at least 8 characters long, enhancing the security of user accounts. The browser will automatically validate the length of the input, and if the entered data is shorter than the specified minlength
, the form will not submit until the requirement is met.
Here's a practical example of how to use it:
<form>
<label for="password">Password:</label>
<input type="password" id="password" name="password" minlength="8" required>
<input type="submit">
</form>
In this example, the <input>
element for a password must contain at least 8 characters for the form to be submitted. The required
attribute is also used to indicate that this field must be filled out. If a user attempts to submit the form with fewer than 8 characters in the password field, the browser will display a validation message, and the form submission will be blocked until the condition is met.
Syntax
<input minlength="number">
Values
- numberThe minimum numeric value in an input field.
Applies To
The minlength
attribute can be used on the following html elements.
Example
<label for="username">Username:</label>
<input type="text" id="username" name="username" minlength="6" required>
<br>
<span id="username-error"></span>
<script>
const usernameInput = document.getElementById('username');
const usernameError = document.getElementById('username-error');
usernameInput.addEventListener('input', () => {
if (usernameInput.value.length < 6) {
usernameError.textContent = "Username must be at least 6 characters long";
} else {
usernameError.textContent = "";
}
});
</script>
Browser Support
The following table will show you the current browser support for the HTML minlength
Attribute.
Desktop | |||||
17 | 40 | 51 | 27 | 10.1 |
Tablets / Mobile | |||||
40 | 51 | 27 | 10.3 | 4 | 40 |
Last updated by CSSPortal on: 26th March 2024