asp.net mvc 4 中的 DataAnnotations 验证(正则表达式)-剃刀视图 [英] DataAnnotations validation (Regular Expression) in asp.net mvc 4 - razor view
问题描述
当在正则表达式中使用特殊字符时,DataAnnotations 验证器在 asp.net mvc 4 razor 视图中不起作用.
The DataAnnotations validator not working in asp.net mvc 4 razor view, when using the special characters in the regular expression.
型号:
[StringLength(100)]
[Display(Description = "First Name")]
[RegularExpression("^([a-zA-Z0-9 .&'-]+)$", ErrorMessage = "Invalid First Name")]
public string FirstName { get; set; }
剃刀视图:
@Html.TextBoxFor(model => Model.FirstName, new { })
@Html.ValidationMessageFor(model => Model.FirstName)
不显眼的验证在视图中呈现为:
The unobtrusive validation is rendered in view as:
<input type="text" value="" tabindex="1" style="height:auto;" name="FirstName" maxlength="100" id="FirstName" data-val-regex-pattern="^([a-zA-Z0-9 .&amp;&#39;-]+)$" data-val-regex="Invalid First Name" data-val-length-max="100" data-val-length="The field FirstName must be a string with a maximum length of 100." data-val="true" class="textfield ui-input-text ui-body-d ui-corner-all ui-shadow-inset valid">
上述html中的regex模式没有按照Model的RegularExpression中指定的方式呈现,导致即使输入有效数据(Sam's
)也会出错.
The regex pattern in the above html is not rendered as specified in the Model's RegularExpression, which results in error even when entering the valid data (Sam's
).
我该如何处理?
--更新--
我已经按照@Rick 的建议更新了代码
I have updated the code as per @Rick suggestion
[StringLength(100)]
[Display(Description = "First Name")]
[RegularExpression("([a-zA-Z0-9 .&'-]+)", ErrorMessage = "Enter only alphabets and numbers of First Name")]
public string FirstName { get; set; }
查看源代码显示以下内容:
View Source shows the following:
<input data-val="true" data-val-length="The field FirstName must be a string with a maximum length of 100." data-val-length-max="100" data-val-regex="Enter only alphabets and numbers of First Name" data-val-regex-pattern="([a-zA-Z0-9 .&amp;&#39;-]+)" id="FirstName" maxlength="100" name="FirstName" type="text" value="" />
我还是有同样的问题.
推荐答案
2012 年 7 月 9 日更新 - 看起来这已在 RTM 中修复.
UPDATE 9 July 2012 - Looks like this is fixed in RTM.
- 我们已经暗示了
^
和$
所以你不需要添加它们.(包含它们似乎没有问题,但您不需要它们) - 这似乎是 ASP.NET MVC 4/Preview/Beta 中的一个错误.我打开了一个错误
- We already imply
^
and$
so you don't need to add them. (It doesn't appear to be a problem to include them, but you don't need them) - This appears to be a bug in ASP.NET MVC 4/Preview/Beta. I've opened a bug
查看源码显示如下:
data-val-regex-pattern="([a-zA-Z0-9 .&'-]+)" <-- MVC 3
data-val-regex-pattern="([a-zA-Z0-9 .&amp;&#39;-]+)" <-- MVC 4/Beta
看起来我们是双重编码.
It looks like we're double encoding.
这篇关于asp.net mvc 4 中的 DataAnnotations 验证(正则表达式)-剃刀视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!