Home > Net >  validate internation phone number in vb6
validate internation phone number in vb6

Time:06-04

I want validate international phone number in vb6 without using regular expressions

only () this charactersand numeric are allowed and it shold be below 20 digits.

What I have tried:

private sub txtPhoneNo_validate ( cancel As boolean)
 if txtPhoneNo = "" then exit sub
 if not Isnumeric(txtPhoneNo) then
    msgbox "phone number shold be in numeric only"
 Elseif len(txtPhoneNo) > 20
    msgbox "phone number shold be in numeric only"
    Exit sub
 end if
end sub

I want to add internation format for validation in my code and () this are the character only allowed

CodePudding user response:

The approach I would suggest, based upon your stated requirements, is to force the user to enter ONLY valid characters:

Option Explicit

Private Sub Form_Load()
   txtPhoneNo.MaxLength = 20
End Sub

Private Sub txtPhoneNo_KeyPress(KeyAscii As Integer)
   'allow only <backspace> <space> ( )   - numeric
   If Not (KeyAscii = 8 Or KeyAscii = 32 Or KeyAscii = 40 Or KeyAscii = 41 Or _
      KeyAscii = 43 Or KeyAscii = 45 Or (KeyAscii >= 48 And KeyAscii <= 57)) Then
      KeyAscii = 0
   End If 
End Sub

In summary, this code enforces a maximum length of 20 characters and discards the keystroke if the key is not a valid character.

This may be sufficient for your needs, but in reality it doesn't really validate the data. For example, the could be entered anywhere in the textbox and still pass our validation. In other words, we are not completely enforcing the rules for international phone numbers. To do so would require much more code or the use of Regular Expressions.

CodePudding user response:

The following answer ensures no more than "20 digits" are included, not just characters. It also ensures that ' ' can only be in the leading position, "-" and " " cannot be in the leading position. While other solutions could be valid, if you wanted to keep with the _Validate() event, or if you want other checks than the basic ones, such as limiting ' ' to only the beginning, this might be of use.

Private Sub txtPhoneNo_Validate(ByRef Cancel As Boolean)
  Const MaxLength As Long = 20
  Dim ANI As String, Cleaned As String
  ANI = txtPhoneNo.Text
  If ANI = "" Then Exit Sub
  
  Dim I As Long, C As String
  For I = 1 To Len(ANI)
    C = Mid(ANI, I, 1)
    
    If IsNumeric(C) Then
      Cleaned = Cleaned & C
    ElseIf C = "(" Or C = ")" Or (I <> 1 And (C = " " Or C = "-")) Or (I = 1 And C = " ") Then
      ' don't count these in count
    Else
      MsgBox "Phone Number should be contain only numbers, parenthesis, a leading plus, and spaces."
      Cancel = True
      Exit Sub
    End If
  
  Next
  If Len(Cleaned) > MaxLength Then
    MsgBox "Phone Number should contain at most 20 digits (provided: " & Len(Cleaned) & ")."
    Cancel = True
    Exit Sub
  End If
End Sub

  • Related