demouser
demouser

Reputation: 113

Decimal validation for greater than zero

I have tried the following Regex to validate decimals that should be greater than zero

@"^-?(?!0(,0+)?$)\d+(,\d{1,3})?$"; and @"^[0-9]+\d*\.\d{3}$" but this is not working as I expected. I need to fire validation when the value is 0.000 in remaining cases it should not.

Valid : 1,123.000
        1.000
        0.001
Invalid : 0 or 0.000

Upvotes: 3

Views: 7370

Answers (2)

Developer
Developer

Reputation: 8636

Try this I tested for few sample and it is working

This worked for me

string expression= @"^(\()?[0-9]+(?>,[0-9]{3})*(?>\.[0-9]{3})?(?<!^[0\.]+)$";

if (Regex.IsMatch("0.000", expression))
{
  //Failed
}

if (Regex.IsMatch("0.001", expression))
{
  //passed
}

if (Regex.IsMatch("1.023", expression))
{
  //passed
}

if (Regex.IsMatch("11,111,111.111", expression))
{
  //passed
}

Upvotes: 2

Richard
Richard

Reputation: 109015

This is very hard to do with a regex, but very easy and much clearer with a conversion function:

decimal d;
if (decimal.TryParse(input, out d) && d > 0.0m) {
  // Valid
} else {
  // Invalid
}

Edit: regular expressions are a very powerful tool for string processing and should be part of every programmers toolbox. But that are not always the right tool: sometimes one needs to reach for something else.

Upvotes: 5

Related Questions