Forbid letters in number field in html5

10,767

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.

Share:
10,767
Rebecca
Author by

Rebecca

I work as a PHP Developer from December 2013, and have experience with core PHP , Codeigniter, Jquery, Javascript etc.

Updated on July 20, 2022

Comments

  • Rebecca
    Rebecca almost 2 years

    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?

  • Rebecca
    Rebecca over 10 years
    Thank You @Mr. Alien worked for me....can u help me with setting the min and max number to input into the text field...thanxx
  • Mr. Alien
    Mr. Alien over 10 years
    @user3114651 Edited my answer :)
  • Jukka K. Korpela
    Jukka K. Korpela over 10 years
    I think you should add a title attribute into the code in the answer, since it is crucial for making error messages understandable (and may give a useful hint on mouseover).
  • Mr. Alien
    Mr. Alien over 10 years
    @JukkaK.Korpela Thanks for reminding me :) I've added that in the demo 2, but didn't pasted the markup here :) doing it now...