Only allow specific characters in textbox
How can I only allow certain characters in a Visual C# textbox? Users should be able to input the following characters into a text box, and everything else should be blocked: 0-9, +, -, /, *, (, ).
I've used Google to look up this problem, but the only solutions I'm getting are allowing only alphabetic characters, only numerical or disallowing certain characters. What I want is not disallowing certain characters, I want to disallow everything by default except the characters that I put in the code.
As mentioned in a comment (and another answer as I typed) you need to register an event handler to catch the keydown or keypress event on a text box. This is because TextChanged is only fired when the TextBox loses focus
The below regex lets you match those characters you want to allow
Regex regex = new Regex(@"[0-9+\-\/\*\(\)]");
MatchCollection matches = regex.Matches(textValue);
and this does the opposite and catches characters that aren't allowed
Regex regex = new Regex(@"[^0-9^+^\-^\/^\*^\(^\)]");
MatchCollection matches = regex.Matches(textValue);
I'm not assuming there'll be a single match as someone could paste text into the textbox. in which case catch textchanged
textBox1.TextChanged += new TextChangedEventHandler(textBox1_TextChanged);
private void textBox1_TextChanged(object sender, EventArgs e)
{
Regex regex = new Regex(@"[^0-9^+^\-^\/^\*^\(^\)]");
MatchCollection matches = regex.Matches(textBox1.Text);
if (matches.Count > 0) {
//tell the user
}
}
and to validate single key presses
textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
// Check for a naughty character in the KeyDown event.
if (System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), @"[^0-9^+^\-^\/^\*^\(^\)]"))
{
// Stop the character from being entered into the control since it is illegal.
e.Handled = true;
}
}
You need to subscribe to the KeyDown
event on the text box. Then something like this:
private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.' && e.KeyChar != '+' && e.KeyChar != '-'
&& e.KeyChar != '(' && e.KeyChar != ')' && e.KeyChar != '*'
&& e.KeyChar != '/')
{
e.Handled = true;
return;
}
e.Handled=false;
return;
}
The important thing to know is that if you changed the Handled
property to true
, it will not process the keystroke. Setting it to false
will.