1

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

huMpty duMpty
  • 14,346
  • 14
  • 60
  • 99

4 Answers4

1

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);
                                  };
Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
0

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.

Me.Name
  • 12,259
  • 3
  • 31
  • 48
  • 1
    Numericupdown wont allow + or whitespace. – General Grey Jun 01 '12 at 15:42
  • True, I read in the responses that the goal is a phone number. The maskedtextbox could do the trick for that, but it would restrict the format, so I don't suppose that would adequate either. – Me.Name Jun 01 '12 at 16:03
  • 1
    Phone numbers? he said whitespace and + I wish people would ask the question they really want answered... – General Grey Jun 01 '12 at 16:57
0

Added

var reg = new Regex(@"^\+?(\d[\d-. ]+)?(\([\d-. ]+\))?[\d-. ]+\d$");

as regex

huMpty duMpty
  • 14,346
  • 14
  • 60
  • 99
0

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.