I need the user to input an Alias. The alias must have no spaces, using only leters or numbers(no #,†,Æ,^ and so on...) how would I do this using VB?
Printable View
I need the user to input an Alias. The alias must have no spaces, using only leters or numbers(no #,†,Æ,^ and so on...) how would I do this using VB?
Using the Validate Event will cover you from the user 'Pasting' data in aswell.
Like:
VB Code:
Option Explicit Const sCompare As String = "abcdefghijklmnopqrstuvwxyz0123456789" Private Sub Text1_Validate() Dim indx As Long For indx = 1 To Len(Text1.Text) If InStr(1, sCompare, Mid$(Text1.Text, indx, 1), vbTextCompare) = 0 Then MsgBox "This isn't alowed : " & """" & Mid$(Text1.Text, indx, 1) & """" Exit For End If Next End Sub
Also,
Highlighting the offending char:
VB Code:
For indx = 1 To Len(Text1.Text) If InStr(1, sCompare, Mid$(Text1.Text, indx, 1), vbTextCompare) = 0 Then MsgBox "This isn't alowed : " & """" & Mid$(Text1.Text, indx, 1) & """" [b]Text1.SelStart = indx - 1 Text1.SelLength = 1 Text1.SetFocus[/b] Exit For End If Next
One thing Bruce missed there was the Cancel paramter to the Validate event. If the data doesn't pass validation, then you should set the Cancel parameter to True. Also, you wont need the SetFocus method since focus won't leave the textbox:This will prevent them from leaving the Textbox until they fix the error.VB Code:
Private Sub Text1_Validate([b]Cancel As Boolean[/b]) Dim indx As Long For indx = 1 To Len(Text1.Text) If InStr(1, sCompare, Mid$(Text1.Text, indx, 1), vbTextCompare) = 0 Then MsgBox "This isn't alowed : " & """" & Mid$(Text1.Text, indx, 1) & """" Text1.SelStart = indx - 1 Text1.SelLength = 1 [b]Cancel = True[/b] Exit For End If Next End Sub
Unfortunatly, I was testing it in VBA.
TextBox's dont have a Validate Event, so I had to rely on memory. And I tested with a CommandButton in lieu of
the Validate Event, hence the need for SetFocus.... :D
Cheers,
Bruce.
Impressive memory! :)
I got it dont worry!
inside the if statment I made a Goto bottom and i just sends it to the "End Sub" and instead of hilighting it i just cleared the text box...