The DataAnnotations validator not working in asp.net mvc 4 razor view, when using the special characters in the regular expression.
Model:
[StringLength(100)] [Display(Description = "First Name")] [RegularExpression("^([a-zA-Z0-9 .&'-]+)$", ErrorMessage = "Invalid First Name")] public string FirstName { get; set; }
Razor View:
@Html.TextBoxFor(model => Model.FirstName, new { }) @Html.ValidationMessageFor(model => Model.FirstName)
The unobtrusive validation is rendered in view as:
<input type="text" value="" tabindex="1" style="height:auto;" name="FirstName" maxlength="100" id="FirstName" data-val-regex-pattern="^([a-zA-Z0-9 .&amp;&#39;-]+)$" data-val-regex="Invalid First Name" data-val-length-max="100" data-val-length="The field FirstName must be a string with a maximum length of 100." data-val="true" class="textfield ui-input-text ui-body-d ui-corner-all ui-shadow-inset valid">
The regex pattern in the above html is not rendered as specified in the Model's RegularExpression, which results in error even when entering the valid data (Sam's
).
How can i handle this?
--UPDATE--
I have updated the code as per @Rick suggestion
[StringLength(100)] [Display(Description = "First Name")] [RegularExpression("([a-zA-Z0-9 .&'-]+)", ErrorMessage = "Enter only alphabets and numbers of First Name")] public string FirstName { get; set; }
View Source shows the following:
<input data-val="true" data-val-length="The field FirstName must be a string with a maximum length of 100." data-val-length-max="100" data-val-regex="Enter only alphabets and numbers of First Name" data-val-regex-pattern="([a-zA-Z0-9 .&amp;&#39;-]+)" id="FirstName" maxlength="100" name="FirstName" type="text" value="" />
Still i have the same issue.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With