Define regular expression validation for custom Data Type in MVC4

advertisements

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 ###-##-####" })

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?

Note: I'd like to keep the validation on the custom data type so I don't have to always remember to add it to each model.

Thanks!


You can have your own custom validator and put it in the model property. here is an example

public class SocialSecurityAttribute : RegularExpressionAttribute
{
    public SocialSecurityAttribute () : base(@"^(\d{3}|###)-(\d{2}|##)-\d{4}$") { }
}

Then register it in the global asax.cs Application start as follows

  DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(SocialSecurityAttribute), typeof(RegularExpressionAttributeAdapter));

When you use it , it will be like any other built in attributes

[SocialSecurity(ErrorMessage ...)]
public string SocialSecurityNumber{get;set;}

I like implementing like this as the code can be reused . Otherwise you can just use RegularExpressionAttribute passsing the regex