Igor S
Igor S

Reputation: 638

Regex to match decimal value

I have the following regex to match decimals:

@"[\d]{1,4}([.][\d]{1,2})?"

but I am able to input multiple decimal dots. How can I prevent this? In general, I can have input strings like "2000" or "2000.22". I have tried to use decimal.TryParse but I can input two decimal dots (e.g. 2000..)

Here is my class with method for validation:

 public static class ValidationUtils
 {
    public static bool IsValid(string text)
    {
        var regex = new Regex(@"^\d{1,9}([.]\d{1,2})?$");
        var success = regex.IsMatch(text);

        return success;
    }
 }

Here is the call in page's code-begind:

private void OnPreviewTextInput(object sender, TextCompositionEventArgs eventArgs)
{
    var box = eventArgs.OriginalSource as TextBox;
    if (box == null) return;
    eventArgs.Handled = !ValidationUtils.IsValid(box.Text + eventArgs.Text);
}

And the xaml of TextBox:

 <TextBox Text="{Binding Nominal, Mode=TwoWay,
 StringFormat={}{0:0.######}, UpdateSourceTrigger=PropertyChanged, 
 NotifyOnValidationError=True, ValidatesOnDataErrors=True,
 Converter={StaticResource  decimalValueConverter}}"
 PreviewTextInput="OnPreviewTextInput"/>

Am I use a wrong event here?

Thanks you.

Upvotes: 3

Views: 5729

Answers (3)

DotNetGeekette
DotNetGeekette

Reputation: 91

You'll need to do a few things. First, you'll want to start with ^ and end with $ to make sure you don't have any unwanted beginning or ending characters. Next, you'll have to escape the . to make it a literal . As you already have noted, you'll want the ? after the grouping as the .## part is not required but allowed.

This makes your final regex the following:

@"^\d{1,4}(\.\d{1,2})?$";

Upvotes: 1

Jerry
Jerry

Reputation: 71538

The issue is that your regex will match up to the last two numbers, if they are present and thus consider the string as a match. You need the anchors to tell the regex that the number should end with the last digits.

^\d{1,4}([.]\d{1,2})$

You don't need to put the square brackets around the \d, and you can use \. to escape the dot, like this:

^\d{1,4}(\.\d{1,2})$

Upvotes: 3

stema
stema

Reputation: 92986

You need to anchor your regex.

@"^\d{1,4}([.]\d{1,2})?$"

^ matches the start of the string

$ matches the end of the string

if you don't do that, you will get partial matches.

Upvotes: 5

Related Questions