Regex to check number starts with '078' and only contains 10 digits

I need to validate a Textbox in my Asp.Net application where the user can enter mobile number and it should starts with 078 and should contain 10 digits.

Sample:

0781234567

here is my code

 public static  bool  CheckPhoneNum(string strPhoneNumber)
    {
        string MatchPhoneNumberPattern = "/^(?=\\d{10,11}$)(07)\\d+/";
        if (strPhoneNumber!= null) return Regex.IsMatch(strPhoneNumber, MatchPhoneNumberPattern );
        else return false;
    }

but it always returns false.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Why don’t you try this? The below regex would validate for phone numbers which should be starts with 078 followed by any 7 digit number.

^078\d{7}$

DEMO

Explanation:

  • ^ Asserts that we are at the start.
  • 078 Matches exactly the digits 078.
  • \d{7} Matches the following 7 digits.
  • $ End of the line.

IDEONE

Solution 2

^078[0-9]{7}$

This is a bit faster than \d if we use only numbers here.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply