Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 797
user1513171 Avatar asked Nov 28 '12 14:11

user1513171


People also ask

How do I restrict only alphabets in HTML?

To restrict user to enter only specific pattern of characters in HTML 5, we use pattern attribute. In the above code snippet, we have pattern attribute value set as [A-Za-z]{3} that forces the user to only enter three alphabets character (not more and not less). No numeric characters will be allowed.

How do you make an HTML input tag only accept numeric values?

You can use the <input> tag with attribute type='number'. This input field allows only numerical values. You can also specify the minimum value and maximum value that should be accepted by this field.


3 Answers

Use html5 pattern attribute for inputs:

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

OR

Use html5 number type for input :

<input type="number" />
like image 126
Akhil Sekharan Avatar answered Oct 21 '22 06:10

Akhil Sekharan


The input textbox

<input type="text" onKeyDown="myFunction()" value="" />

JavaScript

function myFunction() {
    var e = event || window.event;  // get event object
    var key = e.keyCode || e.which; // get key cross-browser

    if (key < 48 || key > 57) { //if it is not a number ascii code
        //Prevent default action, which is inserting character
        if (e.preventDefault) e.preventDefault(); //normal browsers
        e.returnValue = false; //IE
    }
}
like image 27
jonhopkins Avatar answered Oct 21 '22 05:10

jonhopkins


To slightly improve off of jonhopkins excellent answer, I added backspace and delete key acceptance like so:

    function inputValidate(){
   var e = event || window.event;  
   var key = e.keyCode || e.which;                              
   if (((key>=48)&&(key<=57))||(key==8)||(key == 46)) { //allow backspace //and delete
           if (e.preventDefault) e.preventDefault(); 
           e.returnValue = false; 
   }
 }
like image 8
wbt11a Avatar answered Oct 21 '22 06:10

wbt11a