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.3k views
in .Net Framework by 39 42 54
edited by

I am working on an MVC solution and I want to prevent input text from accepting any characters other than Arabic and DOT (.) using regular expressions from frontend and backend MVC.

 


1 Answer

0 like 0 dislike
by 39 42 54
edited by
 
Best answer

How to Prevent input text from accepting any characters other than Arabic and DOT(.) using regular expressions?

To Prevent input text from accepting any characters other than Arabic and DOT(.) 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 only Arabic characters in FrontEnd

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

      $(".arabicWithDot").on("input", function () {
         var inputValue = $(this).val();
         var validChars = /^[\u0600-\u06FF\s.]+$/;
    
         if (!validChars.test(inputValue)) {
             // Remove invalid characters
             $(this).val(inputValue.replace(/[^\u0600-\u06FF\s.]+/g, ''));
         }
     });
    
  3. Add arabicWithDot class to any input type to allow only Arabic character and DOT (.)

          <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 arabicWithDot", @maxlength = "250" })
           @Html.ValidationMessageFor(Model => Model.Position, null, new { @class = "text-danger" })
          </div>
    

MVC Text Box allows only Arabic characters using BackEnd

  1. Open your ViewModel class file
  2. Add the public string Position { get; set; } into ViewModel Class
  3. Add RegularExpression above property allowing only Arabic characters and DOT (.)

           [RegularExpression(@"^[\u0600-\u06FF\s.]+$", ErrorMessage ="Arabic and Dot Only")]
           public string Position { get; set; }
    

Result:

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