Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal validation for greater than zero

Tags:

c#

regex

asp.net

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
like image 730
demouser Avatar asked Dec 12 '25 09:12

demouser


2 Answers

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.

like image 91
Richard Avatar answered Dec 13 '25 23:12

Richard


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
}
like image 41
Developer Avatar answered Dec 13 '25 23:12

Developer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!