为MVC4中的自定义数据类型定义正则表达式验证 [英] Define Regular Expression Validation for custom DataType in MVC4

查看:71
本文介绍了为MVC4中的自定义数据类型定义正则表达式验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将项目从MVC3升级到了MVC4,并注意到我的验证器中的一个不再触发.我将其追踪到Shared/EditorTemplates文件夹中的自定义DataType,该文件夹用于捕获站点中各种形式的社会保险号.(在保存后加载页面时,我们仅显示最后4位数字,以解释正则表达式.)

SSN.cshtml

I upgraded a project from MVC3 to MVC4 and noticed that one of my validators wasn't triggering anymore. I chased it down to a custom DataType in the Shared/EditorTemplates folder that is used for capturing Social Security numbers in various forms across the site. (We only show the last 4 digits when the page is loaded after a save, to explain the regex.)

SSN.cshtml

@{
    var ssn = (string)ViewData.TemplateInfo.FormattedModelValue;
    if (!String.IsNullOrWhiteSpace(ssn)){
        ssn = "###-##-" + Model.Substring(Model.Length - 4, 4);
    }
}
@Html.TextBox("", ssn, new { @class = "text-box single-line ssn", pattern = @"^(\d{3}|###)-(\d{2}|##)-\d{4}$", placeholder = "###-##-####", title = "Expected pattern is ###-##-####" })

似乎在MVC4中,不打扰的验证想要查找 data-val-regex-pattern 作为呈现的文本框的属性,而不仅仅是 pattern .以前有人遇到过这个吗?

It seems like in MVC4 the unobtrusive validation wants to look for data-val-regex-pattern as an attribute of the rendered text box, not just pattern. Has anyone ran into this before?

注意:我想保留对自定义数据类型的验证,因此我不必总是记住将其添加到每个模型中.

谢谢!

推荐答案

我发现,为了使MVC4能够将正确的数据属性呈现给输入字段,我需要用匿名字符中的下划线替换连字符.对象传递给TextBox帮助器.这是我最终得到的代码:

SSN.cshtml

I found out that in order to get MVC4 to render the correct data attributes to the input field, I'd need to replace the hyphens with underscores in the anonymous object passed to the TextBox helper. Here's the code that I ended up with:

SSN.cshtml

@{
    var ssn = (string)ViewData.TemplateInfo.FormattedModelValue;
    if (!String.IsNullOrWhiteSpace(ssn) && ssn.Length == 11)
    {
        ssn = "###-##-" + Model.Substring(Model.Length - 4, 4);
    }
    else {
        ssn = "";
    }
}
@Html.TextBox("", ssn,
    new
    {
        @class = "text-box single-line ssn",
        data_val = "true",
        data_val_regex_pattern = @"^(\d{3}|###)-(\d{2}|##)-\d{4}$",
        data_val_regex = "Expected pattern is ###-##-####",
        placeholder = "###-##-####"
    }
)

这篇关于为MVC4中的自定义数据类型定义正则表达式验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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