Minlength validation in HTML 5 input

HTML 4 has maxlength attribute to limit the number of characters entered in input text box and HTML 5 also supports this attribute as well. HTML 5 input now supports minlength validation using pattern attribute. Let’s see how can we accomplish minimum length for a text box.

Minlength validation in HTML 5 input 

The first and last values entered as property of pattern attribute are minimum and maximum characters limits. Also the required attribute is needed otherwise an input field with an empty value will be excluded from constraint validation.

If you prefer to allow user to keep input empty or enter a certain minimum length then the syntax would be:

Quite easy! We placed one more pattern into our first code example written to let them keep empty or pass minlength validation rule if filled. You can also use regular maxlength attribute as well.

Caveat: It’s the browser’s choice whether or not they use the title attribute to show as the error message. User agents may or may not use the contents of title attribute. To deal with this you need a little JavaScript solution as follow:

You Might Interested In