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 number 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;">
Enter Number
@Html.TextBox("RollNumber", "", new { @class = "form-control", @oninput = "javascript: AllowNumberOnly(this);" })
</div>
}
<script>
var AllowNumberOnly=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. On this event I have called a method named as AllowNumberOnly. This method prevents the user to enter other than number. var AllowNumberOnly=function(cont){
cont.value= cont.value.replace(/[^0-9]/g, "");
}
Now let's check the code for AllowNumberOnly. In this this methos I have accessed the value of the textbox control and used replace function with regular expression to replace the alphabet or any other character which is not a number with blank by maintaining the already entered number. 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 alphabet in you will not be able to add it. Now add some numbers it will allow you.