Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make HTML5 input type="number" accepting dashes

I want to use the number input type for my HTML form.

Unfortunately it only accepts real numbers, no dashes between.

Is there a way to make the number input accepting numbers like "1234-123456789" ?

like image 493
alexwenzel Avatar asked Jan 20 '15 10:01

alexwenzel


People also ask

Which input type in html5 can contain only a numeric value?

By default, HTML 5 input field has attribute type=”number” that is used to get input in numeric format. Now forcing input field type=”text” to accept numeric values only by using Javascript or jQuery. You can also set type=”tel” attribute in the input field that will popup numeric keyboard on mobile devices.


2 Answers

I recently had the same issue. I got around it by using type="tel" instead of type="text" or type="number". By using 'tel' I was able to get a numeric only keyboard on mobile devices and still be able to use my pattern="[0-9\-]+".

Here is the code I used. I hope this is good enough for what you need. They really need to make it so that adding a pattern attribute overrides any built in pattern set by the type attribute.

<input id='zipcode' name='zipcode' type='tel' pattern="[0-9\-]+" placeholder='Zip-code'>

Of course this will only work if all you want is dashes and possibly parentheses.

like image 94
metamilo Avatar answered Sep 22 '22 10:09

metamilo


You can use a regular expression against which the value will be validated. Simply put it in the pattern attribute. You also have to change your input's type to text in order to use that.

 <input type="text" pattern="[0-9]+([-\,][0-9]+)?" name="my-num"
               title="The number input must start with a number and use either dash or a comma."/>
like image 21
Dhru 'soni Avatar answered Sep 20 '22 10:09

Dhru 'soni