控制ViewModel属性验证中的十进制验证错误消息的最佳方法? [英] Best way to control Error Message for decimal validation in ViewModel property validation?

查看:82
本文介绍了控制ViewModel属性验证中的十进制验证错误消息的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ViewModel属性:

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?

谢谢.

推荐答案

您可以使用Range属性作为解决方法.根据此答案,该范围将仅在值存在的情况下进行测试.

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")]

编辑

事实证明,Range仅适用于intdouble.

As it turns out, Range only works for int and double.

另一种方法是实现自定义ClientDataTypeModelValidatorProviderModelValidator.这使您可以完全控制.它们已在Global.asax Application_Start()中注册.每当ModelBinder尝试绑定小数时,这将起作用,无需为每个ViewModel赋予属性.不幸的是,我无法向您展示我们的实现,因为它是公司所有的.使用ILSpy查看MS中的代码.

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

这篇关于控制ViewModel属性验证中的十进制验证错误消息的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆