• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 206
  • Last Modified:

to validate text box

well i have a text box for which i need to validate the user to enter first 4 characters and then 5 numbers
the characters should be 4 and numbers should be 5
so please help
  • 2
1 Solution
Use a masked edit box control, you can set the mask to be ">????99999" which will only allow 4 letters then 5 numbers, with the letters converted to upper case.
Try setting the maxlength to 9. Then in the Validate event, do the following:

Private Sub txtTest_Validate(Cancel As Boolean)

  On Error GoTo txtTest_Validate_Error
  Dim intI          As Integer
  Dim strChar       As String
'Check length of string
  If Len(txtTest) <> 9 Then
    MsgBox "Invalid Length"
    Cancel = True
    Exit Sub
  End If
'Check 1st 4 characters are A-Z
  For intI = 1 To 4
    strChar = UCase(Mid$(txtTest, intI, 1))
'Check character is between 'A' and 'Z'
    If strChar < "A" Or strChar > "Z" Then
      MsgBox "Character " & intI & " is invalid"
      Cancel = True
      Exit Sub
    End If
  Next intI
'Check numerics
  For intI = 5 To 9
    strChar = UCase(Mid$(txtTest, intI, 1))
    If Not IsNumeric(strChar) Then
      MsgBox "Number " & intI & " is invalid"
      Cancel = True
      Exit Sub
    End If
  Next intI
  Exit Sub
  MsgBox Err.Description, , "txtTest_Validate"
  Resume txtTest_Validate_Exit
End Sub

You can either

use the maskedit-Control with the mask-property set to "&&&&#####".
In this case the user isn't allowed to enter other than the predefined chracters


use the LoastFocus-Event of the text box to check the value when the user wants to set the focus to another control

Sub Text1_LostFocus()

If Len(text1) <> 9 Then
   MsgBox("Invalid number of characters")

  If not text1.text like "[a-z][a-z][a-z][a-z][a-z]####"
    MsgBox ("Invalid character format")
  End If

End Sub

or use the Change-Event to check every single character when entered

Sub Text1_Change()
Dim i As Integer
Dim iChar as string
For i=1 To Len(Text1)
   iChar = UCase(Mid(Text1,i,1))
   if (i >= 1 and i <=4 and Not iChar >= "A" and iChar <= "Z") or
     (i >=5 and i<= 9 and Not IsNumeric(ichar))  then
         MsgBox("Invalid character at position " & i)
   End If
End Sub

or use the KeyPress-Event to validate a character before accepting it

Tim, Bobby

Sorry bout that, but your typing rate is at a very high level......

you posted your comments while I was typing an answer, that is just a combination of your two comments

Sorry again


Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now