Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Validate that txtbox contains only letters? 1

Status
Not open for further replies.

daughtery

Programmer
Dec 12, 2006
66
US
How can I validate that a txtbox only contains letters?
 
You can use the like statement to validate this.

ex:

[tt][blue]
If Text1.Text Like "*[!a-zA-Z]*" Then
MsgBox "validation failed"
Else
MsgBox "only letters"
End If
[/blue][/tt]

-George

Strong and bitter words indicate a weak cause. - Fortune cookie wisdom
 
If you want user to type letters only (plus Backspace to delete characters, plus Space):
Code:
Private Sub Text1_KeyPress(KeyAscii As Integer)

Select Case KeyAscii
    Case 97 To 122, 65 To 90, 8, 32
        [green]'97 to 122 a to z
        '65 to 90 A to Z
        '8 Backspace
        '32 Space[/green]
    Case Else
        KeyAscii = 0
End Select

End Sub

Have fun.

---- Andy
 
Andy's method is pretty cool. However, users can probably still copy/paste to the text box, so I suggest you implement BOTH solutions.

Just to clarify... With Andy's solution, I could not press CTRL-V to paste text in to the field, but I could right click the text box and click Paste on the menu that popped up.

-George

Strong and bitter words indicate a weak cause. - Fortune cookie wisdom
 

True statement, gmmastros :)

I have this code as validation for several years now in my apps and users have not figure it out yet how to pass invalid data.

Have fun.

---- Andy
 
>I could not press CTRL-V

However, you can] quite happily use the original Windows Paste key combo: SHIFT-INS

(as a very old, traditional Windows user I use SHIFT-INS as matter of habit rather than the more recent 'I want to be a Mac' variant)
 
Oops, I didn't mention that I need to include for spaces as well. I'm using it in a city textbox as well and need to allow for city names such as "Kansas City". How can update the following to allow spaces as well?


Code:
If strEval Like "*[!a-zA-Z]*" Then
        IsAlpha = False
    Else
        IsAlpha = True
    End If
 
If you would play with it a little, you would find out this:
Code:
    If Text1.Text Like "*[!a-zA-Z ]*" Then
        MsgBox "validation failed"
    Else
        MsgBox "only letters"
    End If
Notice space after Z



Have fun.

---- Andy
 

BTW, you can just use a one-liner:
Code:
IsAlpha = Not (strEval Like "*[!a-zA-Z ]*")
If IsAlpha is a boolean


Have fun.

---- Andy
 
You could possibly just use the edit box's Change event and the edit box's undo method to capture and undo non-alpha insert attempts (using the already mentioned Like operator and SendMessage):

Code:
OptionExplicit
Private Const EM_UNDO = &HC7
Private Const EM_EMPTYUNDOBUFFER = &HCD
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
                                (ByVal hwnd As Long, ByVal wMsg As Long, _
                                ByVal wParam As Long, lParam As Any) As Long
Private Sub Text1_Change()
    Static bCancel As Boolean
    If (Text1.Text Like "*[!a-zA-Z ]*") Then
        bCancel = True
        SendMessage Text1.hWnd, WM_UNDO, 0&, 0&
        Text1.SelStart = Len(Text1.Text)
    End If
        SendMessage Text1.hwnd, EM_EMPTYUNDOBUFFER, 0&, 0&
    bCancel = False
End Sub

If your code needs to be sensitive to the last cursor position, then you may want to also use the Like operator in the KeyPress as well.
 
Remove the lines in the above code with the "bCancel"

When using this method you do sacrifice using the right mouse click context menu's undo, however, if you capture key presses prior to this, then it would only affect the shift inserts.
To that, if you do not check the Change (or Validate) events for non-alpha inserts, the user can additionally use the right mouse to insert.
 
SBertold,
That looks like a useful API call, a star for you.

Should'nt it be;
SendMessage Text1.hWnd, EM_UNDO, 0&, 0&
though?

regards Hugh,
 
Thank you for for the star and for pointing that out,.

EM_UNDO = &HC7
WM_UNDO = &H304

I have both defined in my edit box code bas, and therefore didn't catch it when copying and pasting it.

I am not aware of anything if it makes that much of a difference for a normal text box.

However, I guess you should only use EM_UNDO for a Rich Edit, (which - just to remark - also has a multi-level undo feature(2.0)).

Just to clean it up, here is the changed code.
I added to the example the EM_CANUNDO just in case the action cannot be undone, such as when changing the value in code. I am sure there are other ways this could be done. This is just showing one a simple method which could be built upon.

Code:
Option Explicit
Private Const EM_CANUNDO = &HC6
Private Const EM_UNDO = &HC7
Private Const EM_EMPTYUNDOBUFFER = &HCD
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long

Code:
Private Sub Text1_Change()
    If (Text1.Text Like "*[!a-zA-Z ]*") Then
        If SendMessage(Text1.hwnd, EM_CANUNDO, 0&, 0&) = 0 Then
            Text1.Text = vbNullString
        Else
            SendMessage Text1.hwnd, EM_UNDO, 0&, 0&
            Text1.SelStart = Len(Text1.Text)
        End If
    End If
    SendMessage Text1.hwnd, EM_EMPTYUNDOBUFFER, 0&, 0&
End Sub


Another method you could try out would be to use Edit box's Tag property for the Undo method, which may be easier to work with and have more control over.
Something like this:
Code:
[b]
Private Sub Text1_Change()
    If (Text1.Text Like "*[!a-zA-Z ]*") Then
        If (Text1.Tag Like "*[a-zA-Z ]*") Then
            Text1.Text = Text1.Tag
            Text1.SelStart = Len(Text1.Text)
        Else
            Text1.Text = vbNullString
        End If
    End If
    Text1.Tag = Text1.Text
End Sub
[/b][
 
The crude way to insure no one can ever paste invalid data is by using


Clipboard.Clear

in the mousemove event

like this.




Private Sub Text1_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
Clipboard.Clear
End Sub

And dont worry ctrl v will fail too.

simple ehh
cheers mate


 
oops i said ctrl v will fail but it wont unless you add this
too.

Private Sub Text1_Keypress(KeyAscii As Integer)
If InStr(1, "ABCDEFGHIJKLMNOPQRSTUVWXYZ" & Chr(vbKeyBack), Chr(KeyAscii), vbTextCompare) = 0 Then KeyAscii = 0
End Sub

AND IF YOU WANT USER TO BE ABLE TO SPACE BAR

Private Sub Text1_Keypress(KeyAscii As Integer)
If InStr(1, "ABCDEFGHIJKLMNOPQRSTUVWXYZ " & Chr(vbKeyBack), Chr(KeyAscii), vbTextCompare) = 0 Then KeyAscii = 0
End Sub
 
>Clipboard.Clear
I am not so sure about that. What if the user doesn't use the mouse.
Even if you used the GotFocus, then what happens if the user does a clipboard copy outside of the application?

>And dont worry ctrl v will fail too.
You didn't read this thread throughly?
 
You may have missed my follow up post but yes you
are correct at the first posting
my statement about ctrl v was false
however give this a shot,




start a proj
insert a text box

paste this in form''


try to get anything in there

Private Sub Text1_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
Clipboard.Clear
End Sub

Private Sub Text1_Keypress(KeyAscii As Integer)
If InStr(1, "ABCDEFGHIJKLMNOPQRSTUVWXYZ" & Chr(vbKeyBack), Chr(KeyAscii), vbTextCompare) = 0 Then KeyAscii = 0
End Sub

 
1) I'd really, really hate an application that ate the contents of my clipboard without my explicit permission. Eliminate that bit of your (corrected) solution, and it is no different from Andrzejek's (albeit expressed as an If statement rather than a Case statement)

2) ctrl-v was never a problem with the earlier solutions. It was SHIFT-INS that sneaked it's way around (and the context-sensitive menu)
 

>1) I'd really, really hate an application that ate the contents of my clipboard without my explicit permission

A good point to mention. It is indeed a nasty thing to do.

For example, this happens when the Class Generator Add-In is loaded when a vb project is loaded. The Clipboard contents are removed.
That had aggravated me greatly for a long time, until I figured out what was causing it.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top