HTML5 restricting input characters

2019-02-16 09:31发布

问题:

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

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

回答1:

Use html5 pattern attribute for inputs:

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

OR

Use html5 number type for input :

<input type="number" />


回答2:

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
    }
}


回答3:

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; 
   }
 }


回答4:

For Restricting Characters symbols like '-' and ','

<input type="text" pattern="[^-,]+">

for restricting numbers

<input type="text" pattern="[^0-9]+">

for restricting alphabets

<input type="text" pattern="[^a-zA-Z]+">


回答5:

//improved wbt11a function

function numberFieldStrictInput(allowcomma, allownegative) {
    var e = event || window.event;  // get event object
    var key = e.keyCode ||`enter code here` e.which; // get key cross-browser


    if(key==8 || key==46 || key == 9 || key==17 || key==91 || key==18 || 
            key==116 || key==89 || key==67 || key==88 || key==35 || key==36) //back, delete tab, ctrl, win, alt, f5, paste, copy, cut, home, end
        return true;

    if(key == 109 && allownegative)
        return true;

    if(key == 190 && allowcomma)
        return true;

    if(key>=37 && key<=40) //arrows
        return true;

    if(key>=48 && key<=57) // top key
        return true;

    if(key>=96 && key<=105) //num key
        return true;
    console.log('Not allowed key pressed '+key);

    if (e.preventDefault) e.preventDefault(); //normal browsers
        e.returnValue = false; //IE

}   

//on input put onKeyDown="numberFieldStrictInput(1,0)"


回答6:

var keybNumberAndAlpha = new keybEdit(' 0123456789abcdefghijklmnopqrstuvwxyz');

function keybEdit(strValid, strMsg) {
    var reWork = new RegExp('[a-z]','gi');		//	Regular expression\
    //	Properties
    if(reWork.test(strValid))
            this.valid = strValid.toLowerCase() + strValid.toUpperCase();
    else
            this.valid = strValid;
    if((strMsg == null) || (typeof(strMsg) == 'undefined'))
            this.message = '';
    else
            this.message = strMsg;
    //	Methods
    this.getValid = keybEditGetValid;
    this.getMessage = keybEditGetMessage;
    function keybEditGetValid() {
            return this.valid.toString();
    }
    function keybEditGetMessage() {
            return this.message;
    }
}

function editKeyBoard(ev, objForm, objKeyb) {
    strWork = objKeyb.getValid();    
    strMsg = '';							// Error message
    blnValidChar = false;					// Valid character flag
    var BACKSPACE = 8;
    var DELETE = 46;
    var TAB = 9;
    var LEFT = 37 ;
    var UP = 38 ;
    var RIGHT = 39 ;
    var DOWN = 40 ;
    var END = 35 ;
    var HOME = 35 ;
    
    // Checking backspace and delete  
    if(ev.keyCode == BACKSPACE || ev.keyCode == DELETE || ev.keyCode == TAB 
        || ev.keyCode == LEFT || ev.keyCode == UP || ev.keyCode == RIGHT || ev.keyCode == DOWN)  {
            
        blnValidChar = true;
        
    }
    
    if(!blnValidChar) // Part 1: Validate input
            for(i=0;i < strWork.length;i++)
                    if(ev.which == strWork.charCodeAt(i) ) {
                            blnValidChar = true;
                            break;
                    }
                            // Part 2: Build error message
    if(!blnValidChar) 
    {
                //if(objKeyb.getMessage().toString().length != 0)
                    //		alert('Error: ' + objKeyb.getMessage());
            ev.returnValue = false;		// Clear invalid character
            
            
                ev.preventDefault();
        
            objForm.focus();						// Set focus
    }
}
<input type="text"name="worklistFrmDateFltr" onkeypress="editKeyBoard(event, this, keybNumberAndAlpha)" value="">



回答7:

What about this (it supports special keys, like copy, paste, F5 automatically)?

function filterNumericInput() {
    var e = event || window.event;  // get event object
    if (e.defaultPrevented) {
      return;
    }
    const key = e.key || e.code;
    if ((e.key.length <= 1) && (!(e.metaKey || e.ctrlKey || e.altKey))) {
      if (!((key >= '0' && key <= '9') || (key === '.') || (key === ',') || (key === '-') || (key === ' '))) {
        if (e.preventDefault) {
          e.preventDefault();
        } else {
          e.returnValue = false;
        }
      }
    }
}