51

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;amp;&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;amp;&amp;#39;-]+)" id="FirstName" maxlength="100" name="FirstName" type="text" value="" />

Still i have the same issue.

Prasad
  • 58,881
  • 64
  • 151
  • 199
  • We just had a similar issue where we want a " " to be spit out in the ErrorMessage.. – TweeZz Dec 21 '11 at 13:41
  • Hi, i'm collegue of TweeZz ;] Yes, we've fixed it in the end, but it was rather crude fix. When spitting out unobtrusive validation attributes we htmlDecoded all validation messages for regex validators, you could do the same for your case. – petho Jan 05 '12 at 14:09
  • I have confirmed a differece between MVC 3 tools update and MVC 4 Beta. I've opened a bug and we are investigating. – RickAndMSFT Feb 18 '12 at 02:05
  • We're now rolling back our primary product to MVC3 because of this (we localize heavily, so á etc. being double encoded client side is a big showstopper for us). Would love to get a link to the connect article so we can monitor this... – Terry_Brown May 12 '12 at 07:08
  • Hi Prasad. Did you find a solution for this issue? – hopper Jul 04 '12 at 08:58
  • 1
    Hi teahupoo, We kept it as a known issue in our project as what Microsoft is doing now. Still looking for a fix. Lets hope Microsoft comes with the fix soon. – Prasad Jul 04 '12 at 09:07
  • thanks Prasad. I am having the same problem and not seeing a quick work around... – hopper Jul 04 '12 at 10:04

9 Answers9

36

UPDATE 9 July 2012 - Looks like this is fixed in RTM.

  1. We already imply ^ 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)
  2. This appears to be a bug in ASP.NET MVC 4/Preview/Beta. I've opened a bug

View source shows the following:

data-val-regex-pattern="([a-zA-Z0-9 .&amp;&#39;-]+)"                  <-- MVC 3
data-val-regex-pattern="([a-zA-Z0-9&#32;.&amp;amp;&amp;#39;-]+)"      <-- MVC 4/Beta

It looks like we're double encoding.

Mafii
  • 7,227
  • 1
  • 35
  • 55
RickAndMSFT
  • 20,912
  • 8
  • 60
  • 78
  • Rick, Does it fixes after removing ^ and $? I am still facing the same issue even after removing them. I have updated my question with that implementation. – Prasad Feb 21 '12 at 04:57
  • No, it doesn't change anything. Can you mark this as the correct answer? – RickAndMSFT Feb 22 '12 at 22:38
  • 2
    Rick, I am not sure to mark it as an answer till it solves this issue :) – Prasad Feb 23 '12 at 04:40
  • I just wanted to point other folks to my answer since I work for the MVC team at Microsoft and I've verified/registered the bug. – RickAndMSFT Feb 28 '12 at 00:31
  • Having similar problem. Upvoting so it shows up more on searches. Please advise if any temporary fix is available. – REMESQ Mar 01 '12 at 17:39
  • Rick is right, for sure it is a bug. The &' is Html encoded twice. The first html encoding yields &" The socond encoding html encode again the two & getting: &amp;&#34. There is no easy way to fix. The only way might be to htmldecode the attribute value once it arrive on the client during unobtrusive parsing – Francesco Abbruzzese Mar 26 '12 at 21:53
  • Does a link to the bug exist? I'd like to keep track of it so I know when it's fixed – Phil Hale May 10 '12 at 16:51
  • The bug is fixed in RC which will go public soon. – RickAndMSFT May 17 '12 at 19:15
13

Try escaping those characters:

[RegularExpression(@"^([a-zA-Z0-9 \.\&\'\-]+)$", ErrorMessage = "Invalid First Name")]
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
5

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; }
Bahtiyar Özdere
  • 543
  • 1
  • 7
  • 11
2

This one worked for me, try this

[RegularExpression("^[a-zA-Z &\-@.]*$", ErrorMessage = "--Your Message--")]
crazyCoder
  • 75
  • 1
  • 13
  • 1
    When possible, please make an effort to provide additional explanation instead of just code. Such answers tend to be more useful as they help members of the community and especially new developers better understand the reasoning of the solution, and can help prevent the need to address follow-up questions. – Rajan Jun 10 '20 at 06:40
1

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.

Dismissile
  • 32,564
  • 38
  • 174
  • 263
1

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("&amp;","&");
tagBuilder.MergeAttributes(attrs);

We only cared about & amps, that's why this literal replacement

petho
  • 677
  • 4
  • 10
  • 1
    In general we needed more control over the rendering of certain attributes (http://stackoverflow.com/questions/6016500/changing-the-generated-id-and-name-attributes) so we decided to copy paste (and modify) the MVC source code for certain helper methods. There doesn't seem to be another way.. – TweeZz Jan 05 '12 at 18:25
0

Try this one in model class

    [Required(ErrorMessage = "Enter full name.")]
    [RegularExpression("([A-Za-z])+( [A-Za-z]+)", ErrorMessage = "Enter valid full name.")]

    public string FullName { get; set; }
0

Try using the ASCII code for those values:

^([a-zA-Z0-9 .\x26\x27-]+)$
  • \x26 = &
  • \x27 = '

The format is \xnn where nn is the two-digit hexadecimal character code. You could also use \unnnn to specify a four-digit hex character code for the Unicode character.

Ahmad Mageed
  • 94,561
  • 19
  • 163
  • 174
0

The problem is that the regex pattern is being HTML encoded twice, once when the regex is being built, and once when being rendered in your view.

For now, try wrapping your TextBoxFor in an Html.Raw, like so:

@Html.Raw(Html.TextBoxFor(model => Model.FirstName, new { }))
counsellorben
  • 10,924
  • 3
  • 40
  • 38
  • Though i used @Html.Raw, still the regex renders as encoded. It works fine with my ASP.NET MVC 3 application, the problem is only with MVC4 application. – Prasad Nov 24 '11 at 04:05
  • With @Html.Raw, was the regex still double encoded? In MVC3, I use AntiXSS as the default encoder. My regexes are encoded once, and work without any issue. – counsellorben Nov 24 '11 at 12:22
  • Even when i use @Html.Raw, its encoding. I am using ASP.NET MVC 4 http://www.asp.net/mvc/tutorials/aspnet-mvc-4-mobile-features – Prasad Nov 24 '11 at 12:25