简体   繁体   English

仅接受在JavaScript中不起作用的数字和字母代码

[英]Accept only numbers and letters code not working in JavaScript

I'm trying to prevent user from entering anything except numbers and letters, but my code doesn't even allow them itself. 我试图阻止用户输入除数字和字母以外的任何内容,但是我的代码甚至不允许它们本身输入。 What could be the reason? 可能是什么原因? Here's my code snippet: 这是我的代码段:

$(document).ready(function(){
    $("#txtuname").keypress(function(e){ 
        var validExp = /^[0-9a-z]+$/gi;
        var val = $(this).val();
        if(val.match(validExp))
        {
            $("#errmsg").html("");
            return true;
        }
        else
        {
            $("#errmsg").html("Number and letters Only"); 
            return false;
        }
    });
});


<input type="text" name="txtuname" id="txtuname" />
<span id="errmsg"></span>

JSFiddle JSFiddle

You can use keyup not keypress 您可以使用keyup而不是keypress

 $(document).ready(function(){ $("#txtuname").keyup(function(e){ var validExp = /^[0-9a-z]+$/gi; var val = $(this).val(); if(val.match(validExp)) { $("#errmsg").html(""); return true; } else { $("#errmsg").html("Number and letters Only"); return false; } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <input type="text" name="txtuname" id="txtuname" /> <span id="errmsg"></span> 

You can substitute input event for keypress event; 您可以用input事件代替keypress事件。 adjust RegExp to /[0-9a-z]/i , use .split() with parameter "" , Array.prototype.every() , RegExp.prototype.test() to check each character of input value at if condition; RegExp调整为/[0-9a-z]/i ,将.split()与参数""Array.prototype.every()RegExp.prototype.test()以检查条件if为输入值的每个字符; if each character is a digit or a letter condition is true , else false replace invalid characters of value using .replace() with RegExp /[^0-9a-z]/ig 如果每个字符是数字或字母的条件是true ,否则false替换的无效字符value使用.replace()RegExp /[^0-9a-z]/ig

 $(document).ready(function() { var validExp = /[0-9a-z]/i; $("#txtuname").on("input", function(e) { var val = this.value; var check = val.split("").every(function(value) { return validExp.test(value) }); if (check) { $("#errmsg").html(""); return check; } else { this.value = val.replace(/[^0-9a-z]/ig, ""); $("#errmsg").html("Number and letters Only"); return false; } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <input type="text" name="txtuname" id="txtuname" /> <span id="errmsg"></span> 

$(document).ready(function () {

        $("#txtuname").keypress(function (e) {

            var validExp = /^[0-9a-z]+$/gi;

            if (validExp.test(e.key)) {
                $("#errmsg").html("");
                return true;
            }
            else {
                $("#errmsg").html("Number and letters Only");

                return false;
            }
        });
    });

This is because keypress events are fired before the new character is added to the value of the element (so the first keypress event is fired before the first character is added, while the value is still empty). 这是因为在将新字符添加到元素的值之前触发了keypress事件(因此,在添加第一个字符之前,将触发第一个keypress事件,而该值仍为空)。 You should use keyup instead, which is fired after the character has been added reference . 您应该改用keyup,它是在添加角色reference后触发的。

Here is the code 下面是代码

html html

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 

<input type="text" name="txtuname" id="txtuname" />
<span id="errmsg"></span>

js js

$(document).ready(function(){
    $("#txtuname").keyup(function(e){ 
        var validExp = /^[0-9a-z]+$/gi;
        var val = $(this).val();
        if(val.match(validExp))
        {
            $("#errmsg").html("");
            return true;
        }
        else
        {
            $("#errmsg").html("Number and letters Only"); 
            return false;
        }
    });
});

You issue is you are not getting the value of the key that is being pressed. 您的问题是您没有获得所按下键的值。 If you set the val variable like so, it will work as expected. 如果像这样设置val变量,它将按预期工作。

var val = String.fromCharCode(e.keyCode)

This gets the ASCII code of the key pressed, and then converting to the letter or number it represents. 这将获得按下键的ASCII码,然后转换为它代表的字母或数字。 Then you can check against your regex. 然后,您可以检查您的正则表达式。

 $(document).ready(function(){ $("#txtuname").keyup(function(e){ var validExp = /^[0-9a-z]+$/gi; var val = $(this).val(); if(validExp.test(val)) { $("#errmsg").html(""); return true; } else { // fix the value of input field here $(this).val(""); $("#errmsg").html("Number and letters Only"); return false; } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" name="txtuname" id="txtuname" /> <span id="errmsg"></span> 

  1. You need to use keyup so that the character is "added" already to the value if you're going to use this given technique. 如果要使用此给定的技术,则需要使用keyup,以便字符已经“添加”到该值。

  2. Since String.prototype.match actually returns an array of the match, it won't work in the way you want it to. 由于String.prototype.match实际上返回匹配项的数组,因此它无法以您希望的方式工作。 Not to mention that it is much more expensive than RegEx.prototype.test . 更不用说它比RegEx.prototype.test昂贵得多。

Bonus 奖金

You can use the technique of finding carret position in an input field shown in Get cursor position (in characters) within a text Input field 您可以使用在文本输入字段中的获取光标位置(以字符为单位)中显示的输入字段中查找carret位置的技术

To actually fix the input field on keyup. 实际将输入字段固定在键盘上。

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

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