14,870,416 members
See more:
Hi! all,
I have an application where i have to enter some characters in a textbox, how can i validate it so that the textbox doesn't accept special characters in the beginning of the textbox including a space. It should only allow to enter Characters & Numeric only.
Posted
Updated 5-May-11 2:35am
v2

What characters you consider as "special". Never heard of those :-)
--SA
Nischal Bhatt 6-May-11 1:05am

Hey! SAKryukov, special characters are the following ones:
"!@#\$%^&*()_+-={}[]:";'<>?,./"

## Solution 1

You could use the TextChanged event and if the last character added isn't in a list of acceptable characters, delete it right away from the textbox. be mindful of the caret position though because when you change the text contents, the caret gets reset back tot he beginning of the field.
Nischal Bhatt 5-May-11 9:01am

How can i do it using keypress event?

## Solution 2

The KeyPress Event could miss scenarios such as when a user pastes something into a textbox using only the mouse. In my opinion, John's suggesion of using the TextChanged is a better event to use. Also, you may want to research Regular Expressions.

Here[^] is a C# article that could help give you an idea of how to use them.

butchzn 1-Jun-11 4:50am

Agree on use of Regex. Use asp:RegularExpressionValidator with relevant Regex.

## Solution 4

Inside Class Declare this Function:

```Public Sub txtValidation(ByVal e)
If (Asc(e.KeyChar)) < 65 Or (Asc(e.KeyChar)) > 90 And (Asc(e.KeyChar)) < 97 Or (Asc(e.KeyChar)) > 122 Then

If (Asc(e.KeyChar) <> 32) Then
e.Handled = True
End If
End If
If (Asc(e.KeyChar) = 8) Then
e.Handled = False
End If
End Sub```

The above will avoid you to enter Special Character but allow you to Input Alphabets Only.And the Below given function will avoid you to enter Special Characters but allow you to Enter Numbers only
```Public Sub txtNumberValidation(ByVal e)
If (Asc(e.KeyChar) < 48) Or (Microsoft.VisualBasic.Asc(e.KeyChar) > 57) Then
e.Handled = True

End If
If (Asc(e.KeyChar) = 8) Then
e.Handled = False
End If
End Sub```

Call this Function from your Class to your Form In the Keypress event of your TextBoxes if having Problem follow

I have used ASCII codes to detect the Entered Value.Research on it You Will definitely get your Required Solution.Try it
v3

## Solution 5

Or Finally Try This Function
```Public Sub txtAlphaNumericValidation(ByVal e)
If (Asc(e.KeyChar) < 48) Or (Microsoft.VisualBasic.Asc(e.KeyChar) > 57) And (Asc(e.KeyChar)) < 65 Or (Asc(e.KeyChar)) > 90 And (Asc(e.KeyChar)) < 97 Or (Asc(e.KeyChar)) > 122 Then
e.Handled = True

End If
If (Asc(e.KeyChar) = 8) Then
e.Handled = False
End If
End Sub```

Good Luck !!

## Solution 6

Hi

use this expression ^[A-Za-z0-9]\$
in asp:RegularExpressionValidator

## Solution 7

Use replace method

textbox1.text = textbox1.text.replace("*","").replace("&","")

like this you can remove all special character