validating textbox

A

ameen.abdullah

Hi Guys,

I have a textbox in windows form that should only accept alphabets,
numbers, spaces and underscore. If the textbox contains anyother
character it should display a msg at the time of validation.. Is there
any funciton in vb.net for this? or any other way??


Waiting for ur replies...

Thanks in adv.
 
S

Siva M

There are at least couple of ways to do this: 1. Filtering the charaters in
the Keypress event of the textbox itself 2. Using regular expressions to
find invalid character in the textbox. See which one works ut for you...

Hi Guys,

I have a textbox in windows form that should only accept alphabets,
numbers, spaces and underscore. If the textbox contains anyother
character it should display a msg at the time of validation.. Is there
any funciton in vb.net for this? or any other way??


Waiting for ur replies...

Thanks in adv.
 
G

Guest

Using the KeyPress event does not preclude the user from cutting from some
other source and pasting invalid chars into the text box. Use the textbox's
"Validating" event to check the text for non-alpha characters.
 
C

Claes Bergefall

If you want to prevent illegal characters from being pasted you can use this
code:

Protected Overrides Function ProcessCmdKey(ByRef msg As
System.Windows.Forms.Message, ByVal keyData As System.Windows.Forms.Keys) As
Boolean
'Need to prevent pasting of invalid characters
If keyData = (Keys.Shift Or Keys.Insert) OrElse keyData =
(Keys.Control Or Keys.V) Then
Dim data As IDataObject = Clipboard.GetDataObject
If data Is Nothing Then
Return MyBase.ProcessCmdKey(msg, keyData)
Else
Dim text As String =
CStr(data.GetData(DataFormats.StringFormat, True))
If text = String.Empty Then
Return MyBase.ProcessCmdKey(msg, keyData)
Else
For Each ch As Char In text.ToCharArray
If Not IsValid(ch) Then
Return True
End If
Next
Return MyBase.ProcessCmdKey(msg, keyData)
End If
End If
Else
Return MyBase.ProcessCmdKey(msg, keyData)
End If
End Function

Private Function IsValid(ByVal ch As Char) As Boolean
'TODO: Check if the character is valid
End Function

The above will prevent pasting if the text contains any illegal characters.

/claes
 
C

Claes Bergefall

You're correct. The code below requires an override. If it is enough to
validate when they leave the field then using the Validating event is
easier. I just wanted to point out another option.

/claes
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top