How to Set a Minlength Validation in HTML5

In HTML5, there is a minlength attribute, but as it is not supported in all browsers and when supported, it can cause troubles, we suggest another method of setting the minimal length of value for fields. Anyway, we'll also demonstrate an example with this attribute at the end.

Solution with the HTML pattern and required attributes

In our example below, we set the minimum length of value by using the pattern and required attributes on <input> elements. If the required attribute is not used, an input field having an empty value will be excepted from the constraint validation.

The title attribute is used to allow displaying a message to the user if the pattern isn’t met. If it is not set, a default message will be shown.

Example of using a minlength validation:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      input {
        border: 2px solid #000;
      }
      input:invalid:focus {
        background-image: linear-gradient(#34ebba, #6eeb34);
      }
    </style>
  </head>
  <body>
    <form action="/form/submit" method="post">
      <input pattern=".{2,}" required title="2 characters minimum">
      <input pattern=".{5,8}" required title="5 to 8 characters">
    </form>
  </body>
</html>

Result

If you want an option to use the pattern for an empty or minimum length, try the following example.

Example of setting a minlength validation:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      input {
        border: 2px solid #000;
      }
      input:invalid:focus {
        background-image: linear-gradient(#34ebba, #6eeb34);
      }
    </style>
  </head>
  <body>
    <form action="/form/submit" method="post">
      <input pattern=".{0}|.{5,8}" required title="Either 0 OR (5 to 8 chars)">
      <input pattern=".{0}|.{6,}" required title="Either 0 OR (6 chars minimum)">
    </form>
  </body>
</html>

Example of setting a validation with the HTML minlength attribute:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      input {
        border: 2px solid #cccccc;
      }
      input:invalid:focus {
        background-color: lightblue;
      }
    </style>
  </head>
  <body>
    <form action="/form/submit" method="post">
      <label for="password">Password:
        <input type="password" name="password" id="password" required minlength="8">
      </label>
      <input type="submit" value="Go">
    </form>
  </body>
</html>

Do you find this helpful?

Related articles