Shreekant
Shreekant

Reputation: 469

phone number validation issue

I am trying to validate phone number textbox. I just want user to be able to enter only numeric values and only 10 digits in the textbox. I did it using keypress event.

it works fine but the problem is once the length of the input reaches to 10, it wont even allow the backspace.

Here is my code -

    Private Sub tbphone_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles tbphone.KeyPress
       If Not (Char.IsDigit(CChar(CStr(e.KeyChar))) Or e.KeyChar = ChrW(Keys.Back)) Or tbphone.Text.Length >= 10 Then e.Handled = True
    End Sub

Now, there can be a scenario where user enters all digits correctly but the last one. In that case he will not be able delete that last digit perhaps he will not be able to do anything in that textbox as the length of the input text is already 10 and now the e.handled is set to true.

Please suggest how can I achieve it...

Upvotes: 1

Views: 606

Answers (3)

Eric Sugiharto
Eric Sugiharto

Reputation: 21

i know it is already solved, but if i may add an answer.

    If (e.KeyChar <= ChrW(47)) Or (e.KeyChar >= ChrW(58)) Then
        If e.KeyChar = vbBack Then
        Else
            e.KeyChar = ChrW(0)
        End If
    Else
    End If

i use this code in keypress event

Upvotes: 0

Raymond C.
Raymond C.

Reputation: 598

Disclaimer: I have not touched vb.net in quite some time, say about a year. I am just providing a solution which I used previously and found it helpful.

You may refer to: This question has a similar issue and has been answered.

Regarding your 10 character limit, you can set the MaxLength property of the textbox either via the graphical editor or code.

You may refer to: How to set the textbox MaxLength property. (Please change the language to VB at the top of the page.)

Upvotes: 2

Shreekant
Shreekant

Reputation: 469

I actually found the solution to my own question, I am putting it here so if anyone stuck validating textboxes with the same issue might get help.

I have set the e.handled to false if user presses BackSpace. And it worked...

   Private Sub tbphone_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles tbphone.KeyPress
       If Not Char.IsDigit(CChar(CStr(e.KeyChar))) Or tbphone.Text.Length >= 10 Then e.Handled = True
       If e.KeyChar = ChrW(Keys.Back) Then e.Handled = False
   End Sub

Upvotes: 1

Related Questions