Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I cannot validate a phone number which needs to be at least 9 digits long and a maximum of 11 using visual basic. If I type 1 digit it gives me the error of ("Phone numbers must be at least 9 digits long") but the problem is that I have not pressed the submit button yet. This error should pop up once the user has pressed the submit button not beforehand.

What I have tried:

If Asc(e.KeyChar) <> 8 Then
           If Asc(e.KeyChar) < 46 Or Asc(e.KeyChar) > 57 Or (Asc(e.KeyChar) < 48 And Asc(e.KeyChar) > 46) Then
               e.Handled = True
               MessageBox.Show("Invalid character")
           End If


           If txtBoxPhoneNumber.Text.Length < 9 Then

               MsgBox("Phone numbers must be at least 9 digits long")
               If txtBoxPhoneNumber.Text.Length > 11 Then
                   MsgBox("Phone numbers must be of a maximum of 11 digits long")
               End If

               txtBoxPhoneNumber.Text = ""
               txtBoxPhoneNumber.Focus()

               Exit Sub

           End If
Posted
Updated 21-Dec-17 2:58am

1 solution

You have to perform the check outside the validation function which is called for every key press. That is for example when the user activates a button in the form that contains the input field.

Note also that there is another error in your length check:
You check for long numbers only within the short condition so that that will never be true.

Put something like this in the handler that is executed when the OK button is pressed (or any other event / button):
VB
If txtBoxPhoneNumber.Text.Length < 9 Then
    MsgBox("Phone numbers must be at least 9 digits long")
    txtBoxPhoneNumber.Focus()
End If
If txtBoxPhoneNumber.Text.Length > 11 Then
    MsgBox("Phone numbers must be of a maximum of 11 digits long")
    txtBoxPhoneNumber.Focus()
End If
Note also that I have removed the clearing of the input field so that the user can edit instead of having to enter the full number again.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900