I am trying to make a text-box
which will only accept numbers, white spaces and plus sign.
Currently I have done something like this in KeyPressEvent
of the textbox
if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar) &&!char.IsWhiteSpace(e.KeyChar))
{
e.Handled = true;
}
I want to accept the +
sign as well
Update
I did handle the !char.IsSymbol(e.KeyChar)
but it will accept the =
sign as well with the +
Any help!!!
Thanks
For having "during input" control and validating control, you can make something like that.
But you'll have many things in your textbox (1+++ +2 34+), which doesn't mean a lot...
textBox.KeyDown += (sender, e) =>
{
if (!(
//"+
e.KeyCode == Keys.Add ||
//numeric
(e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9) ||
//space
e.KeyCode == Keys.Space))
{
e.Handled = true;
}
};
textBox.Validating += (sender, eventArgs) =>
{
var regex = new Regex(@"[^0-9\+ ]+");
textBox.Text = regex.Replace(textBox.Text, string.Empty);
};
Strictly speaking you could append
&& !e.KeyChar == '+'
to your criteria and it should work as far as keyboard input is concerned , but if the goal is to only allow numeric input the .net control library also contains a NumericUpDown control that can do the trick.
Added
var reg = new Regex(@"^\\+?(\\d[\\d-. ]+)?(\\([\\d-. ]+\\))?[\\d-. ]+\\d$");
as regex
This works fine for me:
if (!(char.IsLetter(e.KeyChar) && (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar) && !(e.KeyChar == '.'))
{
e.Handled = true;
}
I added the char.IsControl because it allows you to use Backspace in a typeerror case.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.