I can’t get client side validation of regular expressions working with MVC3RTM. All other client side validation works when I comment out the RegularExpression attribute so I know it’s the one causing me problems.
I have a simple model. (SiteText and SiteErrors are just resource files)
public class NewUser {
[Required]
[MultiCulturalDisplayName("UserName", typeof(SiteText))]
public string UserName { get; set; }
[Required]
[AllowHtml]
[RegularExpression(RegExConstants.EmailRegEx, ErrorMessageResourceType = typeof(SiteErrors), ErrorMessageResourceName = "EmailInvalid")]
[DataType(DataType.EmailAddress)]
[MultiCulturalDisplayName("EmailAddress", typeof(SiteText))]
public string Email { get; set; }
[Required]
[ValidatePasswordLength]
[DataType(DataType.Password)]
[MultiCulturalDisplayName("Password", typeof(SiteText))]
public string Password { get; set; }
[DataType(DataType.Password)]
[MultiCulturalDisplayName("PasswordConfirm", typeof(SiteText))]
[Compare("Password", ErrorMessageResourceType = typeof(SiteErrors), ErrorMessageResourceName = "PasswordCompare")]
public string ConfirmPassword { get; set; }
}
Here is the C# escaped regex string that I store in a constant.
^((?>[a-zA-Z\\d!#$%&'*+\\-/=?^_`{|}~]+\\x20*|\"((?=[\\x01-\\x7f])[^\"\\\\]|\\\\[\\x01-\\x7f])*\"\\x20*)*(?<angle><))?((?!\\.)(?>\\.?[a-zA-Z\\d!#$%&'*+\\-/=?^_`{|}~]+)+|\"((?=[\\x01-\\x7f])[^\"\\\\]|\\\\[\\x01-\\x7f])*\")@(((?!-)[a-zA-Z\\d\\-]+(?<!-)\\.)+[a-zA-Z]{2,}|\\[(((?(?<!\\[)\\.)(25[0-5]|2[0-4]\\d|[01]?\\d?\\d)){4}|[a-zA-Z\\d\\-]*[a-zA-Z\\d]:((?=[\\x01-\\x7f])[^\\\\\\[\\]]|\\\\[\\x01-\\x7f])+)\\])(?(angle)>)$
Here is the un-escaped version.
^((?>[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+\x20*|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*"\x20*)*(?<angle><))?((?!\.)(?>\.?[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+)+|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*")@(((?!-)[a-zA-Z\d\-]+(?<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])[^\\\[\]]|\\[\x01-\x7f])+)\])(?(angle)>)$
Could the regex perhaps be too long?
Regular expression arguments aside – have a look at my blog post about how to get Email validation working on the client using ASP.NET MVC 3 and unobtrusive validation.
This approach uses the built-in jQuery Validation email validation and not your own regex. But will use your regex on the server side. I don’t know what sort of regex jQuery validation uses, so this could be a good or bad thing.
ASP.NET MVC 3 Email Validation with Unobtrusive jQuery Validation
It’s extremely simply and if you want to change the regex, just plug your own one in there.
This is the guts of it: