0

I have tried a regex to validate a decimal value as per requirement which works fine for positive integers but when I am making it optional for + or - I am unable to validate it can some one help me this is my expression

ValidationExpression="^[-+][0-9]+(\.([0-9]{1,3})?)?$"

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Learner
  • 351
  • 7
  • 25

2 Answers2

4

You have to make the sign optional with the ? modifier which together with the allowed characters [-+] means zero or one + or -.

ValidationExpression="^[-+]?[0-9]+(\.([0-9]{1,3})?)?$"
halex
  • 16,253
  • 5
  • 58
  • 67
  • +0: while it is answers how to write regular expression similar to one asked it is not the best way to parse numbers. At the very least need to specify cultures where this code will produce correct result and where it fails (`,` is not handled correctly, and `.` as "group separator" is fun too). – Alexei Levenkov Apr 12 '13 at 06:25
2

Do you HAVE to use a regex?

If not, I would recommend using decimal.TryParse(). e.g.

public bool IsValidDecimal(string value)
{
    decimal test;
    return decimal.TryParse(value, NumberStyles.Any, CultureInfo.CurrentCulture, out test);
}

An advantage of using .TryParse() is that it will handle different cultures for you. Different countries use different marks as the decimal delimeter. For example, in the US, . is the delimeter, whereas in Russia , is used.

Alastair Pitts
  • 19,423
  • 9
  • 68
  • 97
  • Deducing from OP's regex he only wants decimals with a maximum of 3 decimal places to be valid. So you need another check for the right number of decimal places. He could use [this answer](http://stackoverflow.com/a/6092298/637284) for this. – halex Apr 12 '13 at 06:14