textbox validation
how to restrict a textbox from accepting special chracters
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Hemant SrivastavaPosted Nov 13, 2013, 9:49 AM
private void txtBx_CountWords_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsLetterOrDigit(e.KeyChar)) // Allowing only any letter OR Digit
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
Hemant SrivastavaPosted Nov 13, 2013, 9:54 AM
Generally one should allow backspace character too alongwith alphanumeric characters
so that user could remove any wrong character if he entered by mistake.
In order to do that, you need to add one more conition in the if block as
private void txtBx_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsLetterOrDigit(e.KeyChar) // Allowing only any letter OR Digit
||e.KeyChar == '\b') // Allowing BackSpace character
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
Let me know if it doesn't solve your problem.
ta muPosted Nov 13, 2013, 7:14 AM
Jaganathan BantheswaranPosted Nov 13, 2013, 3:53 AM
You can do it in server/client side,
Server Side:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
var regex = new Regex(@"[^a-zA-Z0-9\s]");
if (regex.IsMatch(e.KeyChar.ToString()))
{
e.Handled = true;
}
}
Client Side:
Alphanumeric value:
* Special Characters not allowed