Search code examples
c#regexasp.net-mvcmodel-view-controllerdata-annotations

How to validate cell phone number using regular expression in mvc


I want to validate an 11 digit cellphone number which must have 0 and 3 first and then 9 more digit after 03 for example 03XXXXXXXXX

    [Column("ContactNo")]
    [Required(ErrorMessage = "Contact No is required..."), Display(Name = "Contact No")]
    [RegularExpression(@"^\[0]{1}\[3]{1}\d{9}$", ErrorMessage = "Invalid Contact No")]
    public decimal ContactNo { get; set; }

Solution

  • The problem with your regex is that you are using the escape character when you don't need it (This is the backslash). The only one you need is the \d which is used to denote a decimal character.

    In this specific case, \[ means that you want to escape the normal usage of [ and treat it like a literal character.

    So you need to remove the backslashes that are used before the square brackets. So \[ should become [.

    However, you don't need to even use square brackets when you want a single literal character, you can just use 0 and 3 on their own for example.

    With all that in mind, the following regex should work for your requirements:

    ^03\d{9}$
    

    You can see this in action here.


    I would suggest you take some time to read about escape characters and when and where you should use them. This may be a good place to start, though there are certainly plenty of good resources out there.