Reputation: 1459
Consider the following form:
<form>
<input type="text" minlength="5" value="1234">
<button type="submit">submit</button>
</form>
When I click the submit button without changing anything, the minimum length validation doesn't work and the form submits successfully.
But after changing the input value, e.g. 1234 -> 12345 -> 1234
, the validation works and the form does not get submitted.
Why?
Upvotes: 19
Views: 13769
Reputation: 742
You can use placeholder="1234" instead of value="1234" and don't forget to put "required" into your input field. So it works after
<form role="form">
<input type="text" name="number" minlength="5" placeholder="1234" required>
<button type="submit">submit</button>
</form>
Upvotes: 3
Reputation: 25361
The minlength
attribute is not supported in all browsers. You can use the pattern
attribute instead. The required
attribute is also needed, otherwise an input field with an empty value will be excluded from the validation.
Try this:
<form>
<input type="text" pattern=".{5,}" required value="1234">
<button type="submit">submit</button>
</form>
The added benefit of using the pattern
attribute is that it validates initial values, so you will not have the issue that you've seen with the minlength
attribute which doesn't validate initial values (as explained in details by BoltClock's answer). The downside, though, is that the validation message is not as elegant. For example, the message in Chrome is "Please match the requested format" for pattern
and "Please lengthen this text to 5 characters or more" for minlength
.
Upvotes: 11
Reputation: 724342
This is by design. The minlength
attribute only validates a field once it has been edited by the user. It doesn't validate the field if its value hasn't been changed, even if that value doesn't meet the constraint. From the spec (emphasis mine):
Constraint validation: If an element has a minimum allowed value length, its dirty value flag is true, its value was last changed by a user edit (as opposed to a change made by a script), its value is not the empty string, and the JavaScript string length of the element's API value is less than the element's minimum allowed value length, then the element is suffering from being too short.
If you need to validate the value regardless of whether the user has since edited the field, see Racil Hilan's answer (although their statement about the minlength
attribute not being supported everywhere doesn't imply anything and is largely irrelevant — as shown, this is clearly by design; if anything it shows that the browsers that do support the attribute support it fully).
Upvotes: 18