The DataAnnotations validator not working in asp.net mvc 4 razor view, when using the special characters in the regular expression.
Model:
We've had similar issue in the past (as mentioned by TweeZz). In our case we're controlling outputting of TextBoxFor by our custom htmlHelper extension method which is building MvcHtmlString, there in one step we need to add these unobtrusive validation attributes, which is done via
var attrs = htmlHelper.GetUnobtrusiveValidationAttributes(name, metadata)
after call to this method, attributes are html encoded, so we simply check if there was Regular expression validator there and if so, we html unencode this attribute and then merge them into tagBuilder (for building "input" tag)
if(attrs.ContainsKey("data-val-regex"))
attrs["data-val-regex"] = ((string)attrs["data-val-regex"]).Replace("&","&");
tagBuilder.MergeAttributes(attrs);
We only cared about & amps, that's why this literal replacement
This one worked for me, try this
[RegularExpression("^[a-zA-Z &\-@.]*$", ErrorMessage = "--Your Message--")]
Try @ sign at start of expression. So you wont need to type escape characters just copy paste the regular expression in "" and put @ sign. Like so:
[RegularExpression(@"([a-zA-Z\d]+[\w\d]*|)[a-zA-Z]+[\w\d.]*", ErrorMessage = "Invalid username")]
public string Username { get; set; }
Try escaping those characters:
[RegularExpression(@"^([a-zA-Z0-9 \.\&\'\-]+)$", ErrorMessage = "Invalid First Name")]
UPDATE 9 July 2012 - Looks like this is fixed in RTM.
^
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)View source shows the following:
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.
What browser are you using? I entered your example and tried in both IE8 and Chrome and it validated fine when I typed in the value Sam's
public class IndexViewModel
{
[Required(ErrorMessage="Required")]
[RegularExpression("^([a-zA-Z0-9 .&'-]+)$", ErrorMessage = "Invalid First Name")]
public string Name { get; set; }
}
When I inspect the DOM using IE Developer toolbar and Chrome Developer mode it does not show any special characters.