Validating a Phone Number

Simple example of validating a phone number:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' Invalid phone number
     'Dim strPhone As String = "123456789"

    ' valid phone number
    Dim strPhone As String = "(123) 456-7890"
    Dim regexp As New Regex(("^\(?\d{3}\)?\s|-\d{3}-\d{4}$"))

regexp.IsMatch(strPhone) Then
           MsgBox("Valid Phone Number")
          MsgBox("Invalid Phone Number")
   End If

End Sub

Comments (3)
  1. Rod says:

    This is off-topic for your Regex examples, Thom, but I’m just gonna rant here —

    A major pet peeve of mine is systems who insist you enter data in a certain way. Either with forced punctuation (as this example shows), or with "no spaces or dashes allowed" (more common).

    As programmers, it’s our job to allow the user to enter the data *however the heck they want*, then parse it and store it in whatever format *we* want.

    A customer I worked with had a problem that users kept entering incorrect phone numbers. The users were being forced to enter numbers with no spaces, so the visual cue that something was awry was missing.

    If my number is 617-555-1000, it’s easier to spot a typo if my textbox contains "617 555 11000" than "61755511000"

    A more useful code example would be a "Extract only numeric characters from a string (perhaps stripping off ‘1’ if that’s the first digit), and validate the length of it is 10 digits"

    Rant over 🙂


  2. Dave Jenkins says:

    Ummm…I think your regex will match if the area code has only one parenthesis – is this what you want?

    Also, I think your test for whitespace of a dash should be (s|-).

    And finally, I think it fails to match if the dash between the exchange and number is missing – is this what you want?

    You might want to take advantage of some of the regex testing programs that are available on the net. I use the Regex Coach – very cool!

    Good luck…

  3. Thom Robbins says:

    Yes – in this instance i was looking for this exact format. Any other instances or permutations I expected it to fail. Of course this can be expanded to include a variety of other formats.


Comments are closed.

Skip to main content