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:
Javascript 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:


great
ReplyDeleteThe article provides a straightforward example of validating an EmployeeName textbox so that only alphanumeric characters are accepted. Using the onkeypress event and a regular expression makes the validation easy to understand, while the red border and error message give immediate feedback when an invalid character is entered.
ReplyDeleteFor developers learning JavaScript event handling, this is a useful practical example. Javascript Online Training can help build familiarity with events, form validation, regular expressions, and interactive browser-side behavior.
The example also demonstrates how JavaScript can work together with jQuery to update an element's styling and display validation messages dynamically. Practicing similar form-validation scenarios through Javascript Online Training can make these concepts easier to apply in real web applications.
ReplyDelete