I have this simple html:
<input type="text"
placeholder="onlynumbers"
name="onlynumbers"
pattern="\d{1,5}"
maxlength="5">
I need to restrict the number of characters to 5. It works. But I still can type other characters than numbers. I have tried various pattern, for example:
pattern = "[0-9]"
But it is still possible to type other characters than digits.
If I change the type
attribute to number
, then only digits are accepted in the input field but the maxlength
attribute doesn't work. I can enter as many digits as I want. I heard this was a bug in Chrome. Is that the problem?
Is there a cross-browser way to fulfil these requirements:
An input field (text or number, no matters) that only accept digits and doesn't let the user enter more than 5 digits.
You can use the <input> tag with attribute type='number'. This input field allows only numerical values. You can also specify the minimum value and maximum value that should be accepted by this field.
To limit an HTML input box to accept numeric input, use the <input type="number">. With this, you will get a numeric input field. After limiting the input box to number, if a user enters text and press submit button, then the following can be seen “Please enter a number.”
<input type="text" name="country_code" pattern="[0-9]+" title="please enter number only" required="required">
Use max
instead of maxlength
with input type="number"
. For example, to specify max length of 5 digits, use
<input type="number" max="99999" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With