我如何使用jquery阻止或限制输入字段中的特殊字符?

问题描述 投票:104回答:18

如何阻止特殊字符通过jquery输入到输入字段中?

jquery special-characters alphanumeric
18个回答
131
投票

一个使用正则表达式的简单示例,您可以对其进行更改以允许/禁止您喜欢的任何东西。

$('input').on('keypress', function (event) {
    var regex = new RegExp("^[a-zA-Z0-9]+$");
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
    if (!regex.test(key)) {
       event.preventDefault();
       return false;
    }
});

2
投票

这是一个防止用户键入字符“ a”的示例

$(function() {
$('input:text').keydown(function(e) {
if(e.keyCode==65)
    return false;

});
});

1
投票

是的,您可以使用jQuery作为:

<script>
$(document).ready(function()
{
    $("#username").blur(function()
    {
        //remove all the class add the messagebox classes and start fading
        $("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
        //check the username exists or not from ajax
        $.post("user_availability.php",{ user_name:$(this).val() } ,function(data)
        {
          if(data=='empty') // if username is empty
          {
            $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
            { 
              //add message and change the class of the box and start fading
              $(this).html('Empty user id is not allowed').addClass('messageboxerror').fadeTo(900,1);
            });
          }
          else if(data=='invalid') // if special characters used in username
          {
            $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
            { 
              //add message and change the class of the box and start fading
              $(this).html('Sorry, only letters (a-z), numbers (0-9), and periods (.) are allowed.').addClass('messageboxerror').fadeTo(900,1);
            });
          }
          else if(data=='no') // if username not avaiable
          {
            $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
            { 
              //add message and change the class of the box and start fading
              $(this).html('User id already exists').addClass('messageboxerror').fadeTo(900,1);
            });     
          }
          else
          {
            $("#msgbox").fadeTo(200,0.1,function()  //start fading the messagebox
            { 
              //add message and change the class of the box and start fading
              $(this).html('User id available to register').addClass('messageboxok').fadeTo(900,1); 
            });
          }

        });

    });
});
</script>
<input type="text" id="username" name="username"/><span id="msgbox" style="display:none"></span>

1
投票

只是数字:

$('input.time')。keydown(function(e){if(e.keyCode> = 48 &&e.keyCode <= 57){返回true; }其他{返回false; }});


1
投票

[想评论Alex对Dale的回答的评论。不可能的(首先需要多少“ rep”?那不会很快发生..奇怪的系统。)因此作为答案:

可以通过将\ b添加到正则表达式定义中来添加退格,如下所示:[a-zA-Z0-9 \ b]。或者,您只允许整个拉丁语范围,包括或多或少的任何“非奇异”字符(还可以控制字符,如退格键):^ [\ u0000- \ u024F \ u20AC] + $


1
投票

限制按键上的特殊字符。这是关键代码的测试页:http://www.asquare.net/javascript/tests/KeyCode.html

var specialChars = [62,33,36,64,35,37,94,38,42,40,41];

some_element.bind("keypress", function(event) {
// prevent if in array
   if($.inArray(event.which,specialChars) != -1) {
       event.preventDefault();
   }
});

1
投票

要替换特殊字符,请空格并转换为小写

$(document).ready(function (){
  $(document).on("keyup", "#Id", function () {
  $("#Id").val($("#Id").val().replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '').toLowerCase());
 }); 
});

1
投票
$(function(){
      $('input').keyup(function(){
        var input_val = $(this).val();
        var inputRGEX = /^[a-zA-Z0-9]*$/;
        var inputResult = inputRGEX.test(input_val);
          if(!(inputResult))
          {     
            this.value = this.value.replace(/[^a-z0-9\s]/gi, '');
          }
       });
    });

0
投票
[User below code to restrict special character also    

$(h.txtAmount).keydown(function (event) {
        if (event.shiftKey) {
            event.preventDefault();
        }
        if (event.keyCode == 46 || event.keyCode == 8) {
        }
        else {
            if (event.keyCode < 95) {
                if (event.keyCode < 48 || event.keyCode > 57) {
                    event.preventDefault();
                }
            }
            else {
                if (event.keyCode < 96 || event.keyCode > 105) {
                    event.preventDefault();
                }
            }
        }


    });]

0
投票

仅允许文本框中的数字(限制字母和特殊字符)


54
投票

我正在寻找一个答案,将输入内容限制为仅字母数字字符,但仍允许使用控制字符(例如,退格键,删除键,制表符)和复制+粘贴。我尝试提供的所有答案均未满足所有这些要求,因此我使用input事件提出了以下答案。


47
投票

简短回答:


14
投票

使用HTML5的模式输入属性!

<input type="text" pattern="^[a-zA-Z0-9]+$" />

11
投票

看看jQuery字母数字插件。 https://github.com/KevinSheedy/jquery.alphanum

//All of these are from their demo page
//only numbers and alpha characters
$('.sample1').alphanumeric();
//only numeric
$('.sample4').numeric();
//only numeric and the .
$('.sample5').numeric({allow:"."});
//all alphanumeric except the . 1 and a
$('.sample6').alphanumeric({ichars:'.1a'});

10
投票

使用正则表达式允许/禁止任何操作。另外,对于比接受的答案稍微更健壮的版本,可以通过首先传递keypress事件和允许不具有与之关联的键值(退格键,制表符,箭头键,删除等)的字符来完成。根据键码而不是值来检查键。

$('#input').bind('keydown', function (event) {
        switch (event.keyCode) {
            case 8:  // Backspace
            case 9:  // Tab
            case 13: // Enter
            case 37: // Left
            case 38: // Up
            case 39: // Right
            case 40: // Down
            break;
            default:
            var regex = new RegExp("^[a-zA-Z0-9.,/ $@()]+$");
            var key = event.key;
            if (!regex.test(key)) {
                event.preventDefault();
                return false;
            }
            break;
        }
});

10
投票

您的文本框:

<input type="text" id="name">

3
投票

在文本框的onkeypress事件上写一些javascript代码。根据要求在文本框中允许和限制字符]


3
投票

我使用此代码修改我看到的其他代码。如果按下或粘贴的文本通过模式测试(匹配),则只有用户才能写(该示例是仅允许输入8位数字的文本输入)

$("input").on("keypress paste", function(e){
    var c = this.selectionStart, v = $(this).val();
    if (e.type == "keypress")
        var key = String.fromCharCode(!e.charCode ? e.which : e.charCode)
    else
        var key = e.originalEvent.clipboardData.getData('Text')
    var val = v.substr(0, c) + key + v.substr(c, v.length)
    if (!val.match(/\d{0,8}/) || val.match(/\d{0,8}/).toString() != val) {
        e.preventDefault()
        return false
    }
})
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.