Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check the phone number using Regex

I am trying to check the user input, I want the phone number to be like 000-0000.

But my code here does not work as I want. I input

"123-4444444"

and it also matches.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am not familiar with Regex, but I need to use it, so can you tell me how to change the pattern?

Regex regex = new Regex(@"\d{3}-\d{4}");
if (!(regex.IsMatch(txtUpdatePhoneNumber.Text)))
{
   MessageBox.Show("Phone number format should be 000-0000", "Error");
}

>Solution :

You have to specify start and beginning

Please check the regex here: https://regex101.com/r/MZ4YPo/1

^: start of string
$: end of string

^\d{3}-\d{4}$

Regex regex = new Regex(@"^\d{3}-\d{4}$");
if (!(regex.IsMatch(txtUpdatePhoneNumber.Text)))
{
    MessageBox.Show("Phone number format should be 000-0000", "Error");
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading