如何防止将无效字符输入到输入字段中 [英] How to prevent invalid characters from being typed into input fields

查看:223
本文介绍了如何防止将无效字符输入到输入字段中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Onkeydown ,我运行以下JavaScript:

Onkeydown, I run the following JavaScript:

function ThisOnKeyDown(el) {
   if (el.title == 'textonly') {
       !(/^[A-Za-zÑñ-\s]*$/i).test(el.value) ? el.value = el.value.replace(/[^A-Za-zÑñ-\s]/ig, '') : null;
   }
   if (el.title == 'numbersonly') {
       !(/^[0-9]*$/i).test(el.value) ? el.value = el.value.replace(/[^0-9]/ig, '') : null;
   }
   if (el.title == 'textandnumbers') {
       !(/^[A-Za-zÑñ0-9-\s]*$/i).test(el.value) ? el.value = el.value.replace(/[^A-Za-zÑñ0-9-\s]/ig, '') : null;
   }
}

这三个标题属性中的一个被赋予各种输入页面上的字段。只要无效字符被正确删除,代码就会起作用,但直到输入下一个字符为止。我想找到一种简单地拒绝无效输入的方法。感谢您的帮助!

One of these three title attributes is given to various input fields on the page. The code works so far as invalid characters are correctly erased, but not until the next character is entered. I want to find a way to simply deny the invalid input in the first place. I appreciate your help!

编辑:我在全球范围内制作活动。我是这样做的:

Edit: I create the events globally. Here's how I do that:

      function Globalization() {
      var inputs = document.getElementsByTagName('input');
      for (i = 0; i < inputs.length; i++) {
          inputs[i].onfocus = createEventHandler(
              ThisOnFocus, inputs[i]);
          inputs[i].onblur = createEventHandler(
              ThisOnBlur, inputs[i]);
          inputs[i].onkeydown = createEventHandler(
              ThisOnKeyDown, inputs[i]);
          inputs[i].onkeyup = createEventHandler(
              ThisOnKeyUp, inputs[i]);
      }
  }

全球化()运行 body.onload

因此,典型的输入字段包含没有函数调用的HTML这个:

Therefore, a typical input field has HTML without function calls like this:

          <input id="AppFirstName" style="width: 150px;" type="text" maxlength="30" title="textonly"/>


推荐答案

为了防止它被置于首位,您可以在keydown事件处理程序上返回false,从而阻止事件进一步传播。

To prevent it from being set in the first place, you can return false on the keydown event handler, thus preventing the event from propagating any further.

我使用jQuery编写了下面的示例,但是传统绑定时可以使用相同的函数。

I wrote the example below using jQuery, but you can use the same function when binding traditionally.

虽然在服务器端进行验证也很重要,但出于用户友好的考虑,客户端验证非常重要。

Though it's important to validate on the server-side as well, client-side validation is important for the sake of user friendliness.

$("input.number-only").bind({
    keydown: function(e) {
        if (e.shiftKey === true ) {
            if (e.which == 9) {
                return true;
            }
            return false;
        }
        if (e.which > 57) {
            return false;
        }
        if (e.which==32) {
            return false;
        }
        return true;
    }
});

这篇关于如何防止将无效字符输入到输入字段中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆