Question

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.

Was it helpful?

Solution

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);

OTHER TIPS

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 :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top