Best way to control Error Message for decimal validation in ViewModel property validation?

自古美人都是妖i 提交于 2019-12-25 12:13:05

问题


I have a ViewModel property:

public decimal decProperty { get; set; }

I have found it difficult to customise the Error message for the above. However if I code the following, I can specify the error message.

[RegularExpression(@"\d+(\.\d{1,2})?", ErrorMessage = "Invalid decimal")]
public string strProperty { get; set; }

Ideally I just want to keep the type as "decimal?". How could I just specify "Invalid decimal" in this case?

Thanks.


回答1:


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



来源:https://stackoverflow.com/questions/42904883/best-way-to-control-error-message-for-decimal-validation-in-viewmodel-property-v

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!