Allow only Alphanumeric in textbox onkeypress event

In this  article, we will learn how to allow only Alphanumeric in textbox on onkeypress event. If user enter anything except alphanumeric it's prompt a error message in red color below the user entered control.



One day, I was travelling in metro and my right hand side a person was working on Visual Studio 2017 and he opened employee registration page and he was trying to validate EmployeeName textbox but It was not validating. 

Then he called to someone and he asked them how to allow only alphanumeric in our EmployeeName textbox only on onkeypress event of our EmployeeName textbox.

and if user entered any other values except alphanumeric then our control border should on red color and focus on it. One day I thought that , I should write an article on it. So I have create a new simple ASP.NET MVC Application and use it on simple html.

HTML Code:

<script src="~/Scripts/jquery-1.10.2.js"></script>
<label>Employee Name</label>
<input type="text" id="txtEmployeeName" onkeypress="return ValidateUserName(event);" /><br />
<span id="lblErrorMessage" style="color:red"></span>

Javascript code:

I have created a ValidationUserName() for validate username which allow only alphanumeric.

<script type="text/javascript">
    function ValidateUserName(e) {
        var keyCode = e.keyCode || e.which;
        $("#lblErrorMessage").html("");
        $("#txtEmployeeName").css("border", "");
        //Regex for Valid Characters i.e. Alphabets and Numbers.
        var regex = /^[A-Za-z0-9]+$/;

        //Validate TextBox value against the Regex.
        var isValid = regex.test(String.fromCharCode(keyCode));
        if (!isValid) {
            $("#txtEmployeeName").css("border", "1px solid red");
            $("#txtEmployeeName").focus();
           $("#lblErrorMessage").html("Allow only alphanumeric");
        }

        return isValid;
    }
</script>

ValidateUserName(): It allow to enter only alphanumeric values if you try to add any other expect it. This it will so a message in red color and also change the border of Employee Name text. See the result

Demo:


No comments

Powered by Blogger.