Search code examples
javascripthtmlinput

HTML5 restricting input characters


Is it possible to restrict the input of certain characters in HTML5/JavaScript? For example, could I have an input textbox on the screen and if the user tries to type a letter in it, it wouldn't show up in the box because I've restricted it to only numbers?

I know you can use a pattern which will be checked on submit, but I want the "bad" characters to just never be entered at all.


Solution

  • Use html5 pattern attribute for inputs:

    <input type="text" pattern="\d*" title="Only digits" />
    

    OR

    Use html5 number type for input :

    <input type="number" />