Either @Microsoft DJ's answer or @7alhashmi's answer should work fine provided that the decimal separator is the period and not some other character. This holds for US English, but other languages and locales use different separators so for a truly internationalized solution, you cannot rely on that being the case. This makes it difficult to do proper validation using only a regular expression.
Fortunately, there is another possibility: you can leverage decimal.TryParse()
with a culture specifier together with Math.Round()
. For example, if the user's culture is fr-FR
then you could do something like:
string value = "1234,56";
NumberStyles style = NumberStyles.AllowDecimalPoint;
CultureInfo culture = CultureInfo.CreateSpecificCulture("fr-FR"); // or whatever
decimal number;
if (!Decimal.TryParse(value, style, culture, out number))
{
failValidate(FailReason.CannotParse); // Could not parse as a number
}
else if (number != Math.Round(number, 2))
{
failValidate(FailReason.TooManyDecimals); // More than two decimals provided
}
else
{
succeedValidate(); // Number was valid and has at most two decimals
}
Of course, this technique is only really useful on the server side (where you should be doing all the validation that you rely on anyway; client-side validation is a convenience for the user, not something to depend upon for security or input validation).
Using Math.Round() as above will catch the case of the user entering 12.001
, but 12.000
will be accepted since it is equal to 12.00
or for that matter 12
. Depending on your usage scenario this may or may not be acceptable.