user5307298 user5307298 - 1 year ago 49
Javascript Question

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

Answer Source
$(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;
            }
        });
    });