Rebecca
Rebecca

Reputation: 413

Forbid letters in number field in html5

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?

Upvotes: 10

Views: 17382

Answers (1)

Mr. Alien
Mr. Alien

Reputation: 157374

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.

Upvotes: 9

Related Questions