如何在文本字段中禁用非罗马化字符和符号?

时间:2013-05-16 10:12:58

标签: javascript html css forms

我有一个注册页面,我已使用以下代码禁用了用户名字段中的空格键:

<script type='text/javascript'>
//<![CDATA[ 
    $(window).load(function(){
        $("#username").on("keydown", function (e) {
            return e.which !== 32;
        });
    });
//]]>  

</script>

但是,我刚刚发现了导致系统问题的其他角色。如何禁用任何非罗马字符或其他符号?这样的事情:á,#〜!ČΨΩヲЖ

2 个答案:

答案 0 :(得分:1)

您可以使用正则表达式解决此问题。

如果您只想包含字符集A-Z,a-z和0-9(没有重音符号),那么您可以使用以下正则表达式来识别字符是否在这些集合中:

/^[a-zA-Z0-9]/.test(e)

更好的是,当输入无效字符时,您可以在输入旁边输入警告,而不是干扰用户的密钥条目(这可能令人沮丧)。假设您<span id="warning"></span>旁边有<input id="username">

$("#username").on("keydown", function (e) {
    if ( !( /^[a-zA-Z0-9]/.test(e) ) ) {
        $("#warning").text("Only values from a-z, A-Z, and 0-9 are valid");
    }
});

答案 1 :(得分:1)

您可以创建一个charCode范围并精选所需内容:

$("#username").on("keydown", function (e) {
    var charcode = e.which;
    if ( (charcode === 8) || // Backspace
        (charcode >= 48 && charcode <= 57) || // 0 - 9
        (charcode >= 65 && charcode <= 90) || // a - z
        (charcode >= 97 && charcode <= 122)) { // A - Z
        console.log(charcode)
    } else {
        e.preventDefault()
        return
    }
});

http://jsfiddle.net/CC6BW/3/

不要忘记为你不需要的东西阻止默认

拉丁图表在这里: http://www.idautomation.com/product-support/ascii-chart-char-set.html