繁体   English   中英

如何防止用户在长度为0时在文本框中输入特殊字符?

[英]How to prevent user from entering special characters in text box when length is 0?

我有以下代码,当长度为0时,阻止用户输入空格。现在,如何在长度为0时阻止用户输入所有特殊字符(az AZ 0-9以外的任何字符)?

$('#DivisionName').bind('keypress', function(e) {
    if($('#DivisionName').val().length == 0){
        if (e.which == 32){//space bar
            e.preventDefault();
        }
    }
}); 

这是我的文本框。

<input type="text" id="DivisionName" />

字母和数字范围是(包括):

  • 97 - 122(az)
  • 65 - 90(AZ)
  • 48 - 57(0-9)

这是你比较e.which反对。

if (e.which < 48 || 
    (e.which > 57 && e.which < 65) || 
    (e.which > 90 && e.which < 97) ||
    e.which > 122) {
    e.preventDefault();
}

或者,使用逆逻辑:

var valid = (e.which >= 48 && e.which <= 57) || (e.which >= 65 && e.which <= 90) || (e.which >= 97 && e.which <= 122);
if (!valid) {
    e.preventDefault();
}

更新

即便如此,您仍可能希望使用正则表达式整体验证字段内容:

if (/^[A-Z0-9]+$/i.test(value)) {
    // it looks okay now
}

或者通过替换坏东西来修复该字段:

var stripped = value.replace(/[^A-Z0-9]+/i, '');

这就是你要找的东西:

$('#DivisionName').bind('keypress', function(e) {

    if($('#DivisionName').val().length == 0){
        var k = e.which;
        var ok = k >= 65 && k <= 90 || // A-Z
            k >= 97 && k <= 122 || // a-z
            k >= 48 && k <= 57; // 0-9

        if (!ok){
            e.preventDefault();
        }
    }
}); 

或者看到这里: http//jsfiddle.net/D4dcg/

您可以使用正则表达式来验证字符串。 ^[a-zA-z0-9].*

这是一篇关于在javascript中测试正则表达式的文章: http//www.w3schools.com/jsref/jsref_regexp_test.asp

您甚至可以绑定更改事件而不是按键。

暂无
暂无

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

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