Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html pattern to only accept numbers [duplicate]

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.

like image 932
oderfla Avatar asked Dec 12 '17 09:12

oderfla


People also ask

How do you make an HTML input tag only accept numerical values?

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.

How do I restrict input to numbers in HTML?

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.”


2 Answers

<input type="text" name="country_code" pattern="[0-9]+" title="please enter number only" required="required">
like image 70
darshan Avatar answered Oct 06 '22 08:10

darshan


Use max instead of maxlength with input type="number". For example, to specify max length of 5 digits, use

<input type="number" max="99999" />
like image 30
Shreevardhan Avatar answered Oct 06 '22 07:10

Shreevardhan