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.
Download jQuery
https://code.jquery.com/jquery-3.7.1.min.js
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.
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.