0

I have a WPF form where the user is able to enter width and height to scale an image. I want to validate the number with a regular expression. The user should be able to enter only number greater than zero.

At the moment I use the PreviewTextInput event

<TextBox Name="Height" Width="50" PreviewTextInput="Height_ValidateNumber"></TextBox>

and check the input with this method

    private void Height_ValidateNumber(object sender, TextCompositionEventArgs e)
    {
        Regex regex = new Regex("^[1-9][0-9]*$");
        e.Handled = regex.IsMatch(e.Text);
    }

The regex I use is ^[1-9][0-9]\*$

The problem with this is that I'm actully able to enter everything but no digits except zero...

If I am using [^1-9][0-9]\*$ I am able to enter all digits except zero...

I think that the regex ^[1-9][0-9]\*$ is not wrong. I think it is another problem.

Alex
  • 781
  • 10
  • 23
Gerret
  • 2,948
  • 4
  • 18
  • 28

2 Answers2

2

You're filtering all the valid values instead of invalid

Change this

e.Handled = regex.IsMatch(e.Text);

to

e.Handled = !regex.IsMatch(e.Text);

Update1 : e.Text gives newly entered text, you can concatenate TextBox.Text with e.Text to frame full text.

TextBox tb = (TextBox) sender;
Regex regex = new Regex("^[1-9][0-9]*$");
e.Handled = !regex.IsMatch(tb.Text + e.Text);
Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
  • Yea, but I mainly have to problem that I can not enter a zero also after I have entered any digit. – Gerret May 07 '14 at 08:33
  • @Gerret What do you mean by that? You mean `50` is invalid number? – Sriram Sakthivel May 07 '14 at 08:35
  • Yes, 50 should be a valid number. Everything greater than 0 should be a valid number. But if I use my regex I am not able to enter a zero and I do not know why... – Gerret May 07 '14 at 08:37
  • Thank you very much! Did not know that I only get the changed Text it is working now :D – Gerret May 07 '14 at 08:50
1

I know you asked for a RegExpr, but why dont you use:

long number;
if (UInt32.TryParse(e.Text, out number)) 
    // You can use ANY .net Number class here 
    //(you want > 0, use the UInt16,UInt32,UInt64 Structs)

Seems easier and more logical to me :)

Nefarion
  • 872
  • 2
  • 8
  • 28