Allow only Alphabet in textbox using jQuery Asp.Net Core MVC

How to allow user to enter only alphabet in a textbox using jQuery in asp.net core mvc. Simplest and a line code to validate entered value is text.
In today's article I will show you a simple tutorial with an example how to allow only alphabet or text value to a text box in using jQuery in asp.net core mvc. Here we will use regular expressing with replace function to allow enter only alphabet or text value even if user copy and paste the text value. This you can use in asp.net core 6 mvc, asp.net core 8 mvc and even in asp.net mcv.

So, for this article first we will create a new asp.ne core mvc application and add a controller file. In this controller file we will add a HttpGet method, this will act as page load for application. After this create a view and add the jQuery library reference in your view. It is always good to add refence in your Layout page

 @{
	ViewData["Title"] = "Home Page";
	<script src="~/lib/jquery/dist/jquery.min.js"></script>
 } 
Here in above code, I have added jQuery library reference in the header of the page, which is available locally. If you don't have jQuery library on that case, you can download it from below mention link. Now let's check the code for the blocking user to allow enter only alphabet or text value in the textbox. Here I have user Html.TextBox. Now let's check the code.
 @{
	ViewData["Title"] = "Home Page";
	<script src="~/lib/jquery/dist/jquery.min.js"></script>
}
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
	<div style="width:200px;">
		Accept Only Text
		@Html.TextBox("StudentName", "", new { @class = "form-control", @oninput = "javascript: AllowTextOnly(this);" })
	</div>
}
<script>
	var AllowTextOnly=function(cont){
	   cont.value= cont.value.replace(/[0-9]/g, "");
	}
</script> 
In above code I have taken a Html.TexttBox control and in this control, I have defined the name of the control and in attribute section I have taken oninput other than this event any other method will work with the given piece of code. On this event I have called a method named as AllowTextOnly. This method prevents the user to enter other than alphabet or text value.  
	var AllowTextOnly=function(cont){
	   cont.value= cont.value.replace(/[0-9]/g, "");
	}
Now let's check the code for AllowTextOnly. In this this methos I have accessed the value of the textbox control and used replace function with regular expression to replace the number or any other character which is not an alphabet with blank by maintaining the already entered alphabeet or text. Now we have done let's run the code and check the output.

Allow Only alphabet

Now let's check by entering some value to the control first enter numbers in you will not be able to add it. Now add some alphabet it will allow you.
Enter alphabet


Post a Comment