ASP.NET MVC [正则表达式] 属性在整个字符串匹配时不起作用
我似乎在 Stack Overflow 上找不到与此相关的类似主题,所以这里是:
为什么当我针对我的 ASP.NET MVC 视图模型类指定以下定义时:
[Required]
[RegularExpression(@"\A\d{3,4}\Z",
ErrorMessage = "The security code (CVN) must be between 3 - 4 digits long.")]
[Display(Name = "Card Security Code (CVN)")]
public string CardCVN { get; set; }
在我的不显眼的客户端验证测试正则表达式无法验证? (随后显示表单字段错误)。
似乎只要我的正则表达式更改为 [RegularExpression(@"\d{3,4}"...
删除整个字符串匹配技术,它就完美匹配了?而且似乎 jquery 验证呈现,即使它不应用 \A
或 \Z
它只匹配整个字符串匹配(做我最初需要的事情!); ?
谢谢。
I can't seem to find a similar topic on Stack Overflow regarding this, so here goes:
Why is it when I specify against my ASP.NET MVC view model class the following definition:
[Required]
[RegularExpression(@"\A\d{3,4}\Z",
ErrorMessage = "The security code (CVN) must be between 3 - 4 digits long.")]
[Display(Name = "Card Security Code (CVN)")]
public string CardCVN { get; set; }
That on my unobtrusive client side validation test the regular expression cannot be validated? (and subsequently displays a form field error).
It seems as soon as my regex is changed to [RegularExpression(@"\d{3,4}"...
removing the entire string matching technique, it matches perfectly? and it seems the jquery validation that renders, even though it doesn't apply \A
or \Z
it matches only on entire string match anyway (doing what I originally needed!); Am I missing something?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在客户端,正则表达式由 JavaScript 执行,JS 不支持
\A
、\Z
或\z
。您可以使用^
和$
代替,但您不需要这样做。验证器中使用的正则表达式通常自动锚定在两端。我很确定 ASP.NET MVC 就是这种情况。On the client side, the regex is executed by JavaScript, and JS doesn't support
\A
,\Z
or\z
. You could use^
and$
instead, but you shouldn't need to. Regexes used in validators are usually anchored at both ends automatically. I'm pretty sure that's the case with ASP.NET MVC.请改用:
@"^\d{3,4}$"
^
- 字符串开头。$
- 字符串结尾。Use this instead:
@"^\d{3,4}$"
^
- start of string.$
- end of string.