You could use the Range
attribute as a workaround. According to this answer, the range will only be tested if a value exists.
[Range(decimal.MinValue, decimal.MaxValue, ErrorMessage = "Invalid decimal")]
public decimal? decProperty { get; set; }
By the way, you can also define resources so your error messages become translatable.
[Range(decimal.MinValue, decimal.MaxValue, ErrorMessageResourceType = typeof(Resources),
ErrorMessageResourceName = "Decimal_ValidationError")]
EDIT
As it turns out, Range
only works for int
and double
.
Another way is to implement a custom ClientDataTypeModelValidatorProvider
and ModelValidator
. This gives you full control. They are registered in the Global.asax Application_Start()
. This will work every time the ModelBinder tries to bind a decimal, no need to attribute every ViewModel. Unfortunately, I can't show you our implementation, because it is owned by the company. Use ILSpy to take a look at the code from MS.
http://jwwishart.blogspot.co.at/2011/03/custom-server-and-client-side-required.html