简体   繁体   English

如何在 JavaScript 的表单验证中禁用键盘输入

[英]How can I disable keyboard input in form validation for JavaScript

I want to validate a text box so that it only takes numeric values.我想验证一个文本框,以便它只接受数值。 If the user tries to press alphabet keys, the keystrokes must be ignored, ie nothing can be typed in.如果用户尝试按字母键,则必须忽略击键,即不能输入任何内容。

How can this be done?如何才能做到这一点?

Use this code in your HTML page:在您的 HTML 页面中使用此代码:

    <HTML>
   <HEAD>
   <SCRIPT language=Javascript>
      <!--
      function isNumberKey(evt)
      {
         var charCode = (evt.which) ? evt.which : event.keyCode
         if (charCode > 31 && (charCode < 48 || charCode > 57))
            return false;

         return true;
      }
      //-->
   </SCRIPT>
   </HEAD>
   <BODY>
      <INPUT id="txtChar" onkeypress="return isNumberKey(event)" type="text" name="txtChar">
   </BODY>
</HTML>

You might need to use the onkeypress event.您可能需要使用onkeypress事件。

An example which does the opposite thing (input field accepts everything but numbers) can be found here: http://www.w3schools.com/jsref/event_onkeypress.asp可以在此处找到执行相反操作的示例(输入字段接受除数字以外的所有内容): http://www.w3schools.com/jsref/event_onkeypress.asp

how about somthing similar to this类似的东西怎么样

//Bind this keypress function to all of the input tags
$("input").keypress(function (evt) {
//Deterime where our character code is coming from within the event
var charCode = evt.charCode || evt.keyCode;
if (IsNumeric(charCode)) { //key's keycode
return false;
}
});

W3C recommends using the oninput event, which is future proof and takes care of devices which do not have a keyboard. W3C 建议使用oninput事件,它是面向未来的,并且会处理没有键盘的设备。 If your targeted browsers support oninput , do not use any keyboard events.如果您的目标浏览器支持oninput ,请不要使用任何键盘事件。

With HTML5 in modern browsers you can use <input type="number"> (see Dive Into HTML5 for some examples).在现代浏览器中使用 HTML5,您可以使用<input type="number"> (有关示例,请参阅深入了解 HTML5 )。 You'll need a fallback for older browsers though, so here you go.不过,您需要对旧版浏览器进行后备,所以这里是 go。 This works in all major browsers.这适用于所有主要浏览器。 It won't prevent the user from pasting or dragging in non-numeric content, however.但是,它不会阻止用户粘贴或拖动非数字内容。

jsFiddle: http://jsfiddle.net/JCUT2/ jsFiddle: http://jsfiddle.net/JCUT2/

var textBox = document.getElementById("foo");

textBox.onkeypress = function(e) {
   e = e || window.event;
   var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
   if (/\D/.test(String.fromCharCode(charCode))) {
       return false;
   }
};

You can make a javascript function that you will call everytime you press a key in your textbox (with the onkeypress event).您可以制作一个 javascript function ,每次按下文本框中的键(使用 onkeypress 事件)时都会调用它。

  function isNumberKey(evt)
  {
     var charCode = (evt.which) ? evt.which : event.keyCode
     if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

     return true;
  }

Code sample source 代码示例源

I recently was dealing with the same situation (but opposite -- I wanted only alphabetic characters).我最近正在处理同样的情况(但相反——我想要字母字符)。 I initially considered simply using the keypress event, but that has a few fatal flaws:我最初考虑只使用keypress事件,但这有一些致命的缺陷:

  • The user can still paste invalid data into the field;用户仍然可以将无效数据粘贴到字段中;
  • The user can drag invalid text into the field;用户可以将无效文本拖动到字段中;
  • Cancelling the keypress invalidates certain valid input (eg, hotkeys) unless you take special care regarding meta keys (which I'm not positive is possible to do in a robust, complete, and portable manner);取消按键会使某些有效输入(例如,热键)无效,除非您特别注意元键(我不肯定可以以健壮、完整和便携的方式做到这一点);
  • Autocomplete;自动完成;
  • And so on for any number of non-keyboard input methods.对于任意数量的非键盘输入法,依此类推。

Fortunately, at least Firefox and IE9 have a solution: they have an input event that fires for any manner of input method, whether it's a keystroke or a paste operation or whatever.幸运的是,至少 Firefox 和 IE9 有一个解决方案:它们有一个input事件,可以针对任何形式的输入法触发,无论是击键还是粘贴操作等等。 IE<9 doesn't have that, but they do have a paste event to handle the most common use-case, but take care that it fires before the paste actually occurs, so you have to cancel the paste and then do most of the (IE-specific) paste work manually (just a couple of lines of code, but still a bit annoying). IE<9 没有,但它们确实有一个paste事件来处理最常见的用例,但要注意它在实际发生粘贴之前触发,所以你必须取消粘贴,然后执行大部分操作(特定于 IE 的)手动粘贴工作(只需几行代码,但仍然有点烦人)。

I was developing for an internal network that didn't support other browsers, so I haven't researched what WebKit has available.我正在为一个不支持其他浏览器的内部网络进行开发,所以我还没有研究 WebKit 有什么可用的。 The DOM Level 3 spec has a textinput event , but at least Firefox does not support it yet. DOM Level 3 规范有一个textinput event ,但至少 Firefox 还不支持它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM