HTML5限制输入字符

时间:2012-11-28 14:23:13

标签: javascript html5 input

是否可以限制HTML5 / JavaScript中某些字符的输入?例如,我可以在屏幕上有一个输入文本框,如果用户试图输入一个字母,它就不会显示在框中,因为我将其限制为只有数字?

我知道你可以使用会检查提交的模式,但我希望根本不会输入“坏”字符。

9 个答案:

答案 0 :(得分:16)

对输入使用html5 pattern属性:

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

OR

使用html5数字类型输入:

<input type="number" />

答案 1 :(得分:7)

输入文本框

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

答案 2 :(得分:5)

为了略微提高jonhopkins的优秀答案,我添加退格并删除密钥接受,如下:

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

答案 3 :(得分:5)

限制字符符号,如' - '和','

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

限制数字

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

用于限制字母

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

答案 4 :(得分:2)

//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)"

答案 5 :(得分:0)

&#13;
&#13;
<div >
   <select id="ajaxtypes" style="display:inline-block">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
   </select>
   <input type="text" name="type" style="width:100%; background-color:#fff000; display:inline-block;">
</div>
&#13;
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
    }
}
&#13;
&#13;
&#13;

答案 6 :(得分:0)

怎么办(它支持特殊键,例如自动复制,粘贴,F5)?

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

答案 7 :(得分:0)

KeyboardEvent.keyCode已过时,因此这是使用HMLElement.input事件的解决方案。此解决方案使用简单的正则表达式,并且只需从任何输入中删除有问题的元素,就可以很好地处理复制粘贴。

function filterField(e) {
  let t = e.target;
  let badValues = /[^\w\d]/gi;
  t.value = t.value.replace(badValues, '');
}

let inputElement = document.getElementById('myInput');
inputElement.addEventListener('input', filterField);
<input id="myInput" type="text" style="width: 90%; padding: .5rem;" placeholder="Type (almost) anything...">

答案 8 :(得分:0)

将输入限制为字母、数字和“.” (仅适用于 React 用户)

这是我的简单解决方案,我找不到更好的 React 解决方案,所以我自己做了一个。 3 个步骤。

首先,创建一个状态。

const [tagInputVal, setTagInputVal] = useState("");

然后,使用状态作为输入值 (value={tagInputVal}) 并将事件传递给 onChange 处理程序。

<input id="tag-input" type="text" placeholder="Add a tag" value={tagInputVal} onChange={(e) => onChangeTagInput(e)}></input>

然后,在 onChange 处理程序中设置事件的值。

function onChangeTagInput(e) {
    setTagInputVal(e.target.value.replace(/[^a-zA-Z\d.]/ig, ""));
}