Validate currency amounts
I need to accept values which are valid amounts only. The application supports multiple locales so I need to accept amounts in the following formats:
10.05 or 10,05 (in some locale comma is used for decimal separator)
It should not accept values like 10.456 or 10,456
Users are not allowed to enter symbols like dollar, pound or euro. Also no comma separators allowed (for thousands, millions, billions, etc.). Also, no negatives amounts or zero value amounts are allowed.
Is there a built in .NET method to validate this? It is difficult to use regular expression as I need to allow either comma or dot for decimal separator based on the locale.
Take a look at the double.TryParse function that takes multiple parameters and in particular the NumberFormats enumeration. If you are specifying the correct culture, it can handle the comma versus decimal issue. I think you'll need tohandle the negative/zero issue separately though.
I would do the following:
replace , with .
if position of . in string < than stringlength-2 -> not accepted
parse to double, if fails -> not accepted