如何防止用户在长度为0时在文本框中输入特殊字符? [英] How to prevent user from entering special characters in text box when length is 0?

查看:110
本文介绍了如何防止用户在长度为0时在文本框中输入特殊字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

($'$ p
$ b $ $ $ $ $''$'$'$'$' #DivisionName').val()。length == 0){
if(e.which == 32){// space bar
e.preventDefault();
}
}
});

这是我的文本框。

 < input type =textid =DivisionName/> 


解决方案

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


  • 97 - 122(az)
  • 65 - 90(AZ)

  • 48 - 57(0-9)


这就是你比较 e.which 针对。

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

或者使用逆逻辑:

  var valid =(e.which> = 48&& e.which< = 57)|| (即,其中> = 65&<< = 90)|| (例如> = 97& e。,其中<= 122); 
if(!valid){
e.preventDefault();
}

更新
$ b

即使如此,您仍然希望使用正则表达式来验证字段内容:

  if(/^[A-Z0-9]+$/i.test(value)){
//现在好看
}

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

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


I have the following code which prevents user from entering space when the length is 0. Now, how can I prevent user from entering all special characters(anything other than a-z A-Z 0-9) when the length is 0?

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

This is my text box.

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

解决方案

The letter and digit ranges are (inclusive):

  • 97 - 122 (a-z)
  • 65 - 90 (A-Z)
  • 48 - 57 (0-9)

This is what you compare e.which against.

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

Or, using inverse logic:

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

Update

Even so, you may still wish to validate the field contents as a whole using a regular expression:

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

Or fix the field by replacing the bad stuff:

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

这篇关于如何防止用户在长度为0时在文本框中输入特殊字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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