【问题标题】:MVC3 data annotation for regex incorrectly firing正则表达式错误触发的 MVC3 数据注释
【发布时间】:2012-05-31 01:56:05
【问题描述】:

我有一个实体框架 POCO,它的属性定义如下:

[RegularExpression(ValidationHelper.RegularExpressionForDateOnly)]
public virtual DateTime LastBuildDate { get; set; }

常量的定义如下:

public const String RegularExpressionForDateOnly = 
    @"^(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$";

我从 OWASP 那里得到了那个正则表达式:https://www.owasp.org/index.php/OWASP_Validation_Regex_Repository

现在,在 MVC3 视图中,我有:

<tr>
<td class="editor-label">
    @Html.LabelFor(model => model.LastBuildDate)
</td>
<td class="editor-field">
    @Html.EditorFor(model => model.LastBuildDate)
    @Html.ValidationMessageFor(model => model.LastBuildDate)
</td>
</tr>

当我尝试以“05/30/2012”或“5/30/2012”格式输入日期时,验证失败(客户端和服务器端)。如果我手动尝试该正则表达式,该正则表达式应该允许这些格式。但是,当 MVC3 视图使用它进行验证时,验证失败。

还有什么其他原因会导致 MVC 未能通过此正则表达式验证?

【问题讨论】:

    标签: regex asp.net-mvc-3 entity-framework data-annotations


    【解决方案1】:

    我对正则表达式了解的不够多,无法准确地告诉您您做错了什么,但是对于 MVC3 验证器,我绝对推荐 Data Annotations Extension,您也可以在 Nuget 上找到它。 它添加了一堆验证属性,包括日期验证。

    【讨论】:

    • 首先感谢 - 我以前从未遇到过!这是我可以在“服务器端”使用的东西(因为我的模型在不同的程序集中),但我不能使用它的任何 MVC3 部分,因为:“错误 CS1577:程序集生成失败 - 引用程序集” WebActivator' 没有强名称"
    • 实际上 - 做到了,即使没有额外的 MVC3 片段(不管是什么),验证也会按预期工作/失败。我认为 OWASP 正则表达式中一定有一些愚蠢的东西?谁知道。无论如何,谢谢!
    • 没问题。我不确定 MVC3 缺少什么,但我认为还有一个非 MVC3 版本的下载链接应该可以正常工作。
    【解决方案2】:

    提一下,当您需要编写特殊类型的验证时,您可以使用 RemoteValidation 属性(http://msdn.microsoft.com/en-us/library/system.web.mvc.remoteattribute(v=vs.98).aspx),这很简单,因为您不需要制作自定义 DataAnnotation 适配器,然后在 global.asax 中注册您的适配器.

    这是一个例子:

    你的模特:

    [Remote("ValidateSpecialNumber", HttpMethod="Post", 
        ErrorMessage = "You're number isn't special.")]
    public int SpecialNumber { get; set; }
    

    验证时调用的操作:

    [HttpPost]
    public ActionResult ValidateSpecialNumber(int SpecialNumber)
    {
        // validate your number here and return True if validated
        return Json(true);
    }
    

    我指出这一点是因为很少有人知道。

    问候

    【讨论】:

    • 这很酷 - 我以前不知道该属性是如何工作的,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-26
    • 1970-01-01
    • 2014-12-17
    • 2020-07-18
    相关资源
    最近更新 更多