21

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" ?

1

3 Answers 3

21

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Won't this cause issues with accessibility? Will screen readers tell people to enter a phone number?
@Carlin: Good point. This very well might cause an issue with screen readers. As such it isn't a perfect solution, but it's up to the developer as to whether that is an acceptable sacrifice.
Thanks for this, clever little hack. A note: This also seems to allow '/', another character not allowed in number inputs. Using this to get date inputs that use mobile number keypad.
I am sorry for using this comment only to thank you very much for this clever solution. Thank you very much.
Works for Android but not for iPhone (no middle dash button appears)
5

inputmode="numeric" is your new best friend..

https://css-tricks.com/everything-you-ever-wanted-to-know-about-inputmode/#numeric

1 Comment

New since 2019 for major browser. Since 2012 in mobile Firefox. Still (2023) not supported in desktop Safari. caniuse.com/input-inputmode
3

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."/>

1 Comment

Already tried that. But then I loose the nice number keyboard on mobile devices.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.