How to Set a Minimum Character Limit on an HTML input Element?

You can use the minlength attribute (which is very well-supported across different browsers) on the HTML <input> element to enforce minimum number of characters that a user must enter for the input to be valid. For example:

<input type="text" minlength="3" />

This would limit an <input> element to a minimum of 3 (UTF-16 code units) characters.

For a more visual example, you could try the following HTML/CSS code:

<style>
input:invalid { border: 1px solid red; outline: none; }
</style>

<input type="text" minlength="3" required />

This would turn the border of the <input> element red, as long as the input is invalid/empty.

Please note that if no minlength is set on the <input> element, or a non-positive integer value is set, then no minimum character limit is imposed.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.