MVC 2 模型验证消息
我有一个具有如下属性的视图模型:
[RegularExpression(@"^d\+$", ErrorMessageResourceType = typeof(Resources.Validation), ErrorMessageResourceName = "NumberValidationMsg" )]
public int? Number {get; set;}
NumberValidationMsg 资源设置为“仅允许数字!”。
但是当我尝试在表单上的“数字”字段中输入“测试”之类的内容时,ModelState 会显示错误消息,其内容类似于:“值“测试”对于数字无效。”
这个消息可以关闭、自定义吗? (或者最好的解决方案可能只是将 int? 替换为 string )
谢谢!
i have a view model with a property like this one :
[RegularExpression(@"^d\+$", ErrorMessageResourceType = typeof(Resources.Validation), ErrorMessageResourceName = "NumberValidationMsg" )]
public int? Number {get; set;}
NumberValidationMsg resource is set to "Only numbers allowed !".
but when I try to enter something like 'test' into Number field on form, ModelState displays the ErrorMessage with content similar to : "The value 'test' is not valid for Number."
can this message be turned off, customized ?
(or maybe the best solution would be just to replace int? with string )
Thank You !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想接受字段中的文本,则需要将其更改为字符串,并根据您的规则将其转换为 int。
如果你的模型是一个 int,那么唯一有效的输入将是 int (或者空,如果它是“int?”),除非有充分的理由,否则你不应该试图阻止这种情况......此外,我相信你可以省略整个正则表达式,因为 MVC 已经隐式地为您进行了检查(因为它是一个 int)。
If you want to accept text in the field, you need to change it to a string, and make your conversions to int according to your rules.
If your model is an int, then the only valid input will be int (or empty, if it is "int?"), and you should not try to prevent this unless there are good reasons... Moreover, I believe that you could leave the whole regular expression out, because the MVC already does that check for you implicitly (because it is an int).