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
1 2 | <input pattern=".{3,}" required title="Minimum 3 characters required"> <input pattern=".{8, 15}" required title="Input string should be between 8 - 15 characters"> |
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:
1 2 3 | <input pattern=".{0}|.{3,}" required title="Zero or minimum 3 characters required"> <input pattern=".{0}|.{8,15}" required title="Input string should be either empty or between 8 - 15 characters"> |
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.
1 | <input pattern=".{8,}" maxlength="15" required title="Input string should be either empty or between 8 - 15 characters"> |
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:
1 | <input pattern=".{0}|.{3,}" required oninvalid="this.setCustomValidity('Zero or minimum 3 characters required')"> |
This work fine when input is filled wrong first time but after get error you cannot submit wittout refreshing the page
Ishan I’m doubtful that some other script is casuing you the issue. It’s embedded feature in HTML 5 Browser so works fine.
I have added this to my website but when I click submit, even with the correct values entered I am still shown the required message and it does not submit the form?
Hi,
Please provide me url of the page where I can see and check that. You can write us to support@fellowtuts.com as well.
Thanks
Hi Amit, I actually was able to fix this, I had a space in between the comma and the 15 which was causing the error.
Glad to know that you have fixed it.
Thanks…. it worked for me..
thanks it worked
Thanks for this, it worked.
nice post