In the following code I need to modify it so that the btnSave control's click event procedure determines whether the user has entered the phone number in the required format: three digits, a hyphen, three digites, a hyphen, and four digits. If not a message should display saying the format is incorrect. The text box (txtPhone) is used to enter the phone number, the numbers are then added to a text file (phoneNumbers.txt). In the original there are to labe boxes for output, one for the numbers as they appear on the text file(111222333) called lblFileContents, and another after being correctly formatted through code(111-222-3333) called lblFormattedNumbers. Obviously both label boxes will display the same numbers once the code is modified to accept only the proper format(111-222-3333). Here is the original code:

Public Class frmMain

Private Sub btnExit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExit.Click
    Me.Close()
End Sub

Private Sub txtPhone_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtPhone.KeyPress
    ' allows the text box to accept numbers, the hyphen, and the Backspace key

    If (e.KeyChar < "0" OrElse e.KeyChar > "9") AndAlso e.KeyChar <> "-" AndAlso e.KeyChar <> ControlChars.Back Then
        e.Handled = True
    End If
End Sub

Private Sub txtPhone_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtPhone.TextChanged
    lblFileContents.Text = String.Empty
    lblFormattedNumbers.Text = String.Empty
End Sub

Private Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
    ' saves the phone number to a sequential access file

    ' declare variables
    Dim strPhone As String
    Dim outFile As IO.StreamWriter

    ' remove the hyphens
    strPhone = txtPhone.Text.Replace("-", String.Empty)
    ' verify the length
    If strPhone.Length = 10 Then
        outFile = IO.File.AppendText("phoneNumbers.txt")
        outFile.WriteLine(strPhone)
        outFile.Close()
    Else
        MessageBox.Show("Invalid phone number", 
                        "Phone Numbers",
                        MessageBoxButtons.OK, 
                        MessageBoxIcon.Information)
    End If

    ' clear the txtPhone control, then set the focus
    txtPhone.Text = String.Empty
    txtPhone.Focus()
End Sub

Private Sub btnDisplay_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDisplay.Click
    ' displays the phone numbers contained in the file
    ' also displays the phone numbers after inserting hyphens 

    ' declare variables
    Dim inFile As IO.StreamReader
    Dim strPhone As String

    ' clear previous phone numbers from the labels
    lblFileContents.Text = String.Empty
    lblFormattedNumbers.Text = String.Empty

    ' determine whether the file exists
    If IO.File.Exists("phoneNumbers.txt") = True Then
        ' open the file for input
        inFile = IO.File.OpenText("phoneNumbers.txt")
        ' process loop until end of the file
        Do Until inFile.Peek = -1
            ' read a phone number, then display the number
            strPhone = inFile.ReadLine
            lblFileContents.Text = lblFileContents.Text &
                strPhone & ControlChars.NewLine
            ' display the phone number with hyphens
            strPhone = strPhone.Insert(3, "-")
            strPhone = strPhone.Insert(7, "-")
            lblFormattedNumbers.Text =
                lblFormattedNumbers.Text &
                strPhone & ControlChars.NewLine


        Loop
        ' close the file
        inFile.Close()
    Else
        MessageBox.Show("Can't find the phoneNumbers.txt file",
                        "Phone Numbers", MessageBoxButtons.OK,
                        MessageBoxIcon.Information)
    End If
End Sub

End Class

Any help is greatly appreciated.

Dani AI

Generated

Brief summary and practical options (ties to the existing posts by and )

The KeyPress handler in the original post helps while typing but does not stop pasted or malformed input, so the authoritative check needs to happen in btnSave_Click before writing to the file. Two simple, robust options:

  • Prevent bad input up front: use a MaskedTextBox with mask 000-000-0000 so the control only accepts the exact pattern and you can test MaskCompleted before saving.
  • Validate on save: check the exact positions of the two hyphens and ensure every other character is a digit. This avoids relying on keyboard filtering and handles paste operations.

A short, clear VB.NET validation example (run in btnSave_Click) that checks the exact "NNN-NNN-NNNN" shape without using the regex already shown by :

Dim s As String = txtPhone.Text.Trim()
Dim valid As Boolean = (s.Length = 12 AndAlso s(3) = "-"c AndAlso s(7) = "-"c)

If valid Then
    For i As Integer = 0 To s.Length - 1
        If i = 3 Or i = 7 Then Continue For
        If Not Char.IsDigit(s(i)) Then
            valid = False
            Exit For
        End If
    Next
End If

If valid Then
    ' save s (or save digits-only with s.Replace("-", String.Empty))
Else
    MessageBox.Show("Enter phone as 000-000-0000", "Invalid format",
                    MessageBoxButtons.OK, MessageBoxIcon.Information)
End If

Notes and small gotchas

  • 's regex reply is a good alternative when you want a one-line test; his pattern also applied a stricter NANP rule (first digit restrictions) — pick the pattern that matches your rules.
  • Decide a canonical storage format: either keep digits-only in the file (cleaner for processing) and format for display, or store the formatted string and skip the hyphen-insertion step in your display code. If you switch to storing formatted numbers, remove the code that inserts hyphens when reading.
  • Always Trim input and validate on Save so paste/copy and programmatic changes cannot sneak invalid data into the file.

Recommended Answers

All 2 Replies

The easiest way to check is to use a regular expression. Here is an example for your particular requirements:

Imports System.Text.RegularExpressions

Public Class Form1

    Private Sub btnTest_Click(sender As System.Object, e As System.EventArgs) Handles btnTest.Click

        If Regex.IsMatch(txtTestStr.Text, "^[2-9]\d{2}-\d{3}-\d{4}$") Then
            txtResult.Text = "Match"
        Else
            txtResult.Text = "No Match"
        End If

    End Sub

The above sub compares the text in the TextBox, txtTestStr.Text, with the regular expression "^[2-9]\d{2}-\d{3}-\d{4}$" and displays the result in another text box. The regular expression can be broken down as follows

    ^       the start of the string
    [2-9]   any digit in the range 2 to 9
    \d{2}   exactly two other digits
    -       a dash
    \d{3}   exactly three digits
    -       a dash
    \d{4}   exactly four digits
    $       the end of the string

You can find many other useful patterns here

commented: nice +1

"^[2-9]\d{2}-\d{3}-\d{4}$"

Once again you have been very helpful, thank you.

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.