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

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

问题描述

因为我认为人有我没有,可能有一些非标准的解决方案之前,遇到它大量的时间..任何人都可以给任何暗示方向如何prevent从一个文本框输入非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.

推荐答案

我个人觉得与互动有点讨厌的标准模式修修补补,但如果你必须过滤键盘输入,可以通过截取键preSS事件做而且你不想取消的:

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

和它更简洁,prettier使用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();
        }
    });
});

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

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