ASP.Net MVC 2模型验证的正则表达式验证失败 [英] ASP.Net MVC 2 Model Validation Regex Validator fails

查看:178
本文介绍了ASP.Net MVC 2模型验证的正则表达式验证失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的模型元数据类以下属性:

I have following property in my Model Metadata class:

[Required(ErrorMessage = "Spent On is required")]
[RegularExpression(@"[0-1][0-9]/[0-3][0-9]/20[12][0-9]", 
   ErrorMessage = "Please enter date in mm/dd/yyyy format")]
[DataType(DataType.Date)]
[DisplayName("Spent On")]
public DateTime SpentOn { get; set; }

但每当我称之为 ModelState.IsValid 它总是返回false,因为正则表达式是没有验证。我一直在使用相同的模式匹配针对新的正则表达式输入的日期(2010年8月29日),它完美地匹配。

But whenever I call ModelState.IsValid it always returns false because regex is not validating. I have matched the entered date (08/29/2010) against new regex using same pattern and it matches perfectly.

我在做什么错了?

推荐答案

这是因为正则表达式适用于字符串,而不是的DateTime 属性。如果用户输入无法从模型解析到的DateTime 实例无效字符串粘合剂将你的正则表达式前添加一个通用的错误信息执行。

That's because regex applies to strings and not DateTime properties. If the user enters an invalid string which cannot be parsed to a DateTime instance from the model binder it will add a generic error message before your regex pattern executes.

您有几个可能性:


  1. Customize在资源文件中的错误信息

  2. 编写自定义模型绑定

  3. 使用的字符串属性(我感到内疚,提出这项: - ))

这篇关于ASP.Net MVC 2模型验证的正则表达式验证失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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