防止在文本框中输入非 ascii 字符 [英] prevent typing non ascii characters in a textbox

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

问题描述

因为我认为人们在我之前已经遇到了很多时间,并且可能有一些标准的解决方案.. 任何人都可以给出任何提示方向如何防止用户在文本框中输入非 ascii 字符.

Since I think people have encounter it lots of time before I did and there may be some standart solution.. Can anybody give any hint direction how to prevent a user from typing non ascii characters in a textbox.

推荐答案

我个人觉得修改标准交互模式有点烦人,但是如果你必须过滤键盘输入,你可以通过拦截按键事件并取消那些你不想要的:

I personally find tinkering with standard modes of interaction a bit annoying, but if you must filter keyboard input, you can do it by intercepting key press events and canceling the ones that you don't want:

var allowed = /[a-zA-Z0-9]/; // etc.

window.onload = function () {
    var input = document.getElementById("test");

    input.onkeypress = function () {
        // Cross-browser
        var evt = arguments[0] || event;
        var char = String.fromCharCode(evt.which || evt.keyCode);

        // Is the key allowed?
        if (!allowed.test(char)) {
            // Cancel the original event
            evt.cancelBubble = true;
            return false;
        }
    }
};

而且使用 jQuery 更简洁漂亮:

And it's more concise and prettier with jQuery:

var allowed = /[a-zA-Z0-9]/; // etc.

$(function () {
    var input = document.getElementById("test");

    $("#input").keypress(function (e) {
        // Is the key allowed?
        if (!allowed.test(String.fromCharCode(e.keyCode || e.which))) {
            // Cancel the original event
            e.preventDefault();
            e.stopPropagation();
        }
    });
});

这篇关于防止在文本框中输入非 ascii 字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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