Step 1: Add this function in your View:
- $(document).ready(function () {
- $(".digit").keypress(function (e) {
- if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
- $("#errormsg").html("Digits Only").show().fadeOut("slow");
- return false;
- }
- });
- });
Step 2: Add a span next to the TextBoxFor to show the error message and the class name we are using should be same.
Here i have given class name as "digit" and using it when the key is pressed:
- <li>
- @Html.LabelFor(x => x.company.ContactNumber)
- @Html.TextBoxFor(x => x.company.ContactNumber, new { @class = "digit" })
- <span id="errormsg"></span>
- </li>
The textbox will accept only numbers, backspace and delete keys.
I had given the respective key codes in the jquery function.