Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
0 like 0 dislike
1.5k views
in .Net Framework by 39 42 54
edited by

I am working on an MVC solutions and I want to allow input text from accepting only numeric using regular expressions from frontend and backend mvc  .


1 Answer

1 like 0 dislike
by 39 42 54
 
Best answer

How to allow input text accepting numeric using regular expressions ?

To enable input text to accept numeric values using regular expressions in MVC, you should follow the below steps:

  1. Navigate to the _Layout.cshtml file .
  2. Add the <script></script> tags below.

MVC Text Box allow Number using FrontEnd

  1. Open _Layout.cshtml file
  2. Add the <script></script> tags below

      $(".numeric").on("input", function () {
         var inputValue = $(this).val();
         var validChars = /^[0-9]+$/;
    
         if (!validChars.test(inputValue)) {
             // Remove invalid characters
             $(this).val(inputValue.replace(/[^0-9]+/g, ''));
         }
     });
    
  3. Add numeric class to any input type to allow numeric

          <div class="mb-3 col-xs-12 col-sm-6 col-md-6 col-lg-6">
           @Html.Label("Resource.Label.JobTitle", new { @class = " form-label", @for = "Position" })
           <span style="color: red;">*</span>
           @Html.TextBoxFor(m => m.Position, new { @class = "form-control numeric", @maxlength = "14" })
           @Html.ValidationMessageFor(Model => Model.Position, null, new { @class = "text-danger" })
          </div>
    

MVC Text Box allow Number using BackEnd

  1. Open your ViewModel class file
  2. Add the public string Position { get; set; } into ViewModel Class
  3. Add RegularExpression above property allow only Numeric

           [RegularExpression(@"^[0-9]+$", ErrorMessage ="Only Numeric")]
           public string Position { get; set; }
    

Result :

If you don’t ask, the answer is always NO!
...