Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forbid letters in number field in html5

Tags:

html

forms

input

I want to prevent the user from entering non-numeric characters in a textfield for telephone number in HTML5. I tried this, but it doesn't forbid non-numeric characters:

<input type="tel"  name="usrtel"><br>

I tried using type=number as well, but that gives me a up and a down arrow to increase or decrease the value, which is not useful for telephone numbers. How can I accomplish this?

like image 229
Rebecca Avatar asked Dec 27 '13 07:12

Rebecca


1 Answers

You can use pattern attribute with a regex \d*

<input type="tel" name="usrtel" pattern="\d*" />

Demo (After typing in the box, just click anywhere outside the box, if you type in anything except the integers, it will show a red box, else it will stay normal)

Demo 2 (With custom message and submit button)


As you commented, you can change your pattern value to ^[0-9]{3,45}$ where user will have to input minimal of 3 digits to maximum of 45 in length.

Demo

<input 
      type="tel" 
      name="usrtel" 
      pattern="^[0-9]{3,45}$" 
      title="You can only enter numbers, with a minimal of 3 characters 
      upto 45 characters are accepted."
      required="required" 
/>

In the above markup, am using a title which will throw a custom error to your user.

like image 97
Mr. Alien Avatar answered Oct 02 '22 06:10

Mr. Alien