James
James

Reputation: 15

how can i limit inputbox to 11 numerical values in vb

How can I limit an inputbox to 11 numerical values in vb? I would like to enable a person to edit a phone number but seem to be having issue with my current code.

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    For Each x As ListViewItem In lvCustomers.Items
        Dim contactEdit As String
        If x.Checked Then
            contactEdit = CInt(InputBox("Modify contact no."))
            Do Until contactEdit.Count = 11
                MessageBox.Show("Maximum numerical digits of 11")
            Loop

            x.SubItems(5).Text = contactEdit

            x.Checked = False

        End If
    Next
End Sub

Upvotes: 1

Views: 167

Answers (2)

Sebastian Brosch
Sebastian Brosch

Reputation: 43594

You can use Regex to check this:

Imports System.Text.RegularExpressions
'[...]
Dim isValid As Boolean = Regex.Match("12345", "^\d{0,11}$").Success()

Your code can look like this:

Imports System.Text.RegularExpressions
'[...]
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    For Each x As ListViewItem In lvCustomers.Items
        Dim contactEdit As String

        If x.Checked Then
            contactEdit = InputBox("Modify contact no.")

            Do Until Regex.Match(contactEdit, "^\d{0,11}$").Success()
                MessageBox.Show("Maximum numerical digits of 11")
                contactEdit = InputBox("Modify contact no.")
            Loop

            x.SubItems(5).Text = contactEdit
            x.Checked = False
        End If
    Next
End Sub

You can define the minimum and maximum length of the input on the RegExp ({minValue,maxValue}). The input have to be numeric (\d). You can find a explanation of the used RegExp on this site: https://regex101.com/r/6h7z2u/1

Hint: I recommend to remove the CInt from InputBox because the code throws an Exception if the value from InputBox isn't a valid Integer. With the used RegExp of the solution, only numbers can written to the InputBox.

Upvotes: 1

vishal paalakurthi
vishal paalakurthi

Reputation: 138

You can Use Len(contactEdit.Text) = 11 Instead of contactEdit.Count = 11

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    For Each x As ListViewItem In lvCustomers.Items
        Dim contactEdit As String
        If x.Checked Then
            contactEdit = CInt(InputBox("Modify contact no."))
            Do Until Len(contactEdit.Text) >= 11
                MessageBox.Show("Maximum numerical digits of 11")
            Loop
            x.SubItems(5).Text = contactEdit
            x.Checked = False
        End If
    Next
End Sub

Upvotes: 0

Related Questions