CSS Portal

HTML minlength Attribute

If this site has been useful, we’d love your support! Consider buying us a coffee to keep things going strong!

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

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 information will show you the current browser support for the HTML minlength attribute. Hover over a browser icon to see the version that first introduced support for this HTML attribute.

This attribute is supported by all modern browsers.
Desktop
Chrome
Edge
Firefox
Opera
Safari
Tablets & Mobile
Chrome Android
Firefox Android
Opera Android
Safari iOS
Samsung Internet
Android WebView
-

Last updated by CSSPortal on: 26th March 2024

If this site has been useful, we’d love your support! Consider buying us a coffee to keep things going strong!