How to Set a Minlength Validation in HTML5
In this snippet, find out what alternative attributes to minlength can be used to set a minlength validation in HTML5. Read our snippet and try examples.
In HTML5, the <span class="attribute">minlength</span> attribute is the standard and widely supported way to set a minimum length for input fields. However, if you need more complex validation or want to support older browsers, you can use the <span class="attribute">pattern</span> and <span class="attribute">required</span> attributes. Below, we demonstrate both approaches.
Solution with the HTML pattern and required attributes
In our example below, we set the minimum length of value by using the <span class="attribute">pattern</span> and <span class="attribute">required</span> attributes on <input> elements. If the <span class="attribute">required</span> attribute is not used, an input field having an empty value will be exempted from the constraint validation.
The <span class="attribute">title</span> 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
<div class="demo px-2.5 mt-1 mb-5 not-prose"> <form action-xhr="/form/submit" method="post"> <input pattern=".\{2,\}" required="" title="2 characters minimum"> </input> <input pattern=".\{5,8\}" required="" title="5 to 8 characters"> </input> </form> </div> If you want to use the <span class="attribute">pattern</span> attribute for minimum length validation, 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=".{5,8}" required title="5 to 8 characters" />
<input pattern=".{6,}" required title="6 characters minimum" />
</form>
</body>
</html>Example of setting a validation with the HTML <span class="attribute">minlength</span> 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>