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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Hemant SrivastavaRank #581 · 4.2K reputationPosted Nov 13, 2013, 4:49 AM EST
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;
}
}
Jaganathan BantheswaranRank #170 · 14.1K reputationPosted Nov 12, 2013, 10:53 PM EST
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
ta mu198 reputationPosted Nov 13, 2013, 2:14 AM EST
Hemant SrivastavaRank #581 · 4.2K reputationPosted Nov 13, 2013, 4:54 AM EST
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.