User007 User007 - 4 months ago 13
C# Question

How to validate decimal places

Please let me know good way to validate decimal value, if decimal(4,2) it should accept 2 numeric and 2 decimal places.

var value = "44.29";
var dec = value.Split('.');


Then finding the length will can be used, I need a better culture specific way. I need a generic solution which can be applied to all decimal field.

Like:

validate(int before,int afterdecimal);
var valid = validate(2,2);


Need a generic cleaner solution for this

private static bool IsDecimal(string value, int before, int after)
{
if (value.Contains("."))
{
var parts = value.Split('.');

if (parts[0].Length == before && parts[1].Length == after)
return true;
}
else if(value.Length == before)
return false;
return true;
}

Answer

You can try like this:

[RegularExpression(@"^\d{1,2}(\.\d{0,2})$",ErrorMessage = "Value contains more than 2 decimal places")]
public decimal Value { get; set; }