I'm trying to validate the correct format for a phone number in a text box: (000) 000-0000

For a test, i made it so that a messagebox shows up saying "correct" if the format is correct. This test works well WHEN the format is correct. BUT when the format IS NOT correct, I keep getting an error saying that the index was out of the array.

How can I fix it? Here's what I have...

ElseIf phonenumbertxtbox.Text.Length <> 0 Then
            If phonenumbertxtbox.Text.Chars(0) <> "(" And phonenumbertxtbox.Text.Chars(4) <> ")" Then
                MessageBox.Show("incorrect")
            Else
                MessageBox.Show("correct")
            End If

I only tested the (000) because I wanted to see if i could get it to work before completing the code.

Please help! Thank you!

Dani AI

Generated

Good news: the exception is just from indexing into the string before it is long enough. Rather than checking fixed character positions, validate the whole input at once. is on the right track with a pattern check; in VB the Like pattern you want is: If phonenumbertxtbox.Text Like "(###) ###-####" Then .... That avoids index errors and keeps the rule simple.

If you want something stricter and easier to extend, use a regular expression that anchors the entire string and allows an optional space after the area code:

Imports System.Text.RegularExpressions

If Regex.IsMatch(phonenumbertxtbox.Text, "^\(\d{3}\)\s?\d{3}-\d{4}$") Then
    MessageBox.Show("correct")
Else
    MessageBox.Show("incorrect")
End If

This matches only NANP numbers like (123) 456-7890, with or without the space. Using Regex.IsMatch centralizes the rule and prevents out-of-range indexing. (learn.microsoft.com)

Two UI-friendly options you can drop in today:

  • WinForms: use a MaskedTextBox with Mask = "(000) 000-0000", then check MaskCompleted/MaskFull in Validating. This enforces the format as the user types and eliminates manual parsing. (learn.microsoft.com)
  • ASP.NET Web Forms: add a RegularExpressionValidator next to the TextBox with ValidationExpression="^\(\d{3}\)\s?\d{3}-\d{4}$". If the field must not be blank, pair it with a RequiredFieldValidator. The validator docs also recommend anchoring patterns with ^ and $ to avoid partial matches. (learn.microsoft.com)

Finally, instead of message boxes, consider showing inline feedback so users can correct mistakes without interruption (WinForms ErrorProvider is built for this). (learn.microsoft.com)

Recommended Answers

All 3 Replies

You Might look into using regular expressions or the Like operator:

If phonenumbertxtbox.Text Like "$$$-$$$-$$$$" Then Msgbox ("Correct")

Regular expressions are more advanced, but you can do more checking with them.

See if this helps.

'//------- Pre-requisites: 1 Button, 1 TextBox named "phonenumbertxtbox". -------\\
Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        With phonenumbertxtbox
            If Not .Text = Nothing Then '// check if not empty.
                If .Text.Length > 0 AndAlso .Text.Substring(0, 1) = "(" Then '// check if length is greater than 0 and if first char. is "(".
                    If .Text.Length > 4 AndAlso .Text.Substring(4, 1) = ")" Then '// check if length is greater than 4 and if 5th char. is ")".
                        If .Text.Length > 8 AndAlso .Text.Substring(8, 1) = "-" Then '// check if length is greater than 8 and if 9th char. is "-".
                            MsgBox("Correct")
                        Else : MsgBox("Incorrect")
                        End If
                    Else : MsgBox("Incorrect")
                    End If
                Else : MsgBox("Incorrect")
                End If
            End If
        End With
    End Sub


    Private Sub phonenumbertxtbox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles phonenumbertxtbox.KeyPress
        Select Case e.KeyChar
            Case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "(", ")", "-", vbBack '// your pre-selected Characters and Backspace.
                e.Handled = False '// allow.
            Case Else
                e.Handled = True '// block.
        End Select
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        phonenumbertxtbox.MaxLength = 13 '// set max. allowed characters.
    End Sub
End Class
commented: How can I convert this code without a button click +0

validating textbox in vb.net email_id,mobile num,name,date,address plz give me the code

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.