Mvc validation regular expression only numbers?

36,590

Solution 1

/ / is javascript way to build a regular expression literal object. In .NET you should not use it.

Try the following:

@"^\((\d{10}?)\)$"

or if you want exactly 10 digits:

@"^(\d{10})$"

Solution 2

If don't have any restrictions other than numbers only, this should fit:

[RegularExpression(@"^\d+$", ErrorMessage = "Please enter proper contact details.")]
[Required]
[Display(Name = "Contact No")]
public string ContactNo { get; set; }
Share:
36,590
Neo
Author by

Neo

Hi! I'm a software engineer. Having experience to work on C#,Asp.Net,AJAX,SQL 2005/08/2012,EF4,SQL to LINQ and also worked on Cloud Computing (Microsoft Windows Azure and AWS Amazon).

Updated on February 08, 2020

Comments

  • Neo
    Neo about 4 years

    I tried the following code for digits-only validation for a contact number validation in Mvc web app.

    [RegularExpression(@"/(^\(\d{10})?)$/", ErrorMessage = "Please enter proper contact details.")]
    [Required]
    [Display(Name = "Contact No")]
    public string ContactNo { get; set; }
    

    But the validation expression is not working.

    For the contact number I want to only accept digits. It can be either a 10 digit mobile number or a land-line number.

  • Zapnologica
    Zapnologica over 8 years
    so basically you use a regex to determine if the string is all digits.
  • Admin
    Admin over 8 years
    Thanks sir, your answer actualy help to me