3

I am getting an HTML encoded value out of MVC's [RegularExpression] validator when it writes the code to the client. This isn't an issue for the error message (since it should be encoded for later display), but it is really screwing up the regex :) On a string field, my regular expression looks like this:

[RegularExpression(@"^[^\<\>]*$", ErrorMessage = "May not contain <,>")]

When this gets written out by mvc3, it shows up looking like this:

<input ... data-val-regex-pattern="^[^\&amp;lt;\&amp;gt;]*$" 
           data-val-regex="May not contain &amp;lt;,&amp;gt;" .../>

Edit:

  • Because of the encoding, it was also catching <>, but also tripping up on words with:
  • t like tim
  • g like goat
  • probably ; but I didn't test it

The purpose of this regex is to filter out < and >, rather than disable all validation on the page and preform it on the server side. This field accepts multiple unicode langages, and is only 12 chars long.

My choices look like:

  1. Disable asp.net input sanity checks on one page and check that in the action only
  2. Find a complex regex to match 3+ unicode ranges +/- dashes & numbers - .net + js compat.
  3. Write a custom regex validator that doesn't have client side validation
  4. Use a [Remote] validator to do it on the server side like we do for other fields

I'm leaning towards #3 now, but I would really like to find a way to keep to built-in functionality. Is there any way to disable this output escaping?

2
  • also you can use remote validation to do this
    – cpoDesign
    May 25, 2012 at 7:26
  • Yes, of course. Seems quite excessive for a regex though, but it should be on the list of possible solutions.
    – Andrew
    May 25, 2012 at 10:13

2 Answers 2

4

It took me a while, but I found out what seems obvious now: use unicode literals instead of the actual characters <>.

My regex ended up like this, and works in both .Net & JS

// \u003c = <,  \u003e = >
[RegularExpression(@"^[^\u003C\u003E]*$", ErrorMessage = "...")]

I ended up with a custom validation attribute to keep from having that code everywhere. Better would be a custom "default" object adapter & custom jquery validation for this regex, thus allowing a second regex for format to be attached. Work for another day. Here is the custom class & validation:

Custom subclass of regular expression attribute:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class RegexUnsafeChars : RegularExpressionAttribute
{
    public RegexUnsafeChars() : base(@"^[^\u003C\u003E]*$")
    {
        base.ErrorMessage = "May not contain <,>";
    }
}

Because this is a custom attribute, and the provider only checks for EXACT matches, we need to declare the adapter manually. Thankfully we can re-use the built-in regex one. Add this code in Application_Start() in Global.asax.cs

DataAnnotationsModelValidatorProvider.RegisterAdapter(
            typeof(RegexUnsafeChars), 
            typeof(RegularExpressionAttributeAdapter));
0

jQuery validation should work fine and it did work fine indeed when I tested. The values are properly encoded.

Model:

public class MyViewModel
{
    [DataType(DataType.MultilineText)]
    [RegularExpression(@"^[^\<\>]*$", ErrorMessage = "May not contain <,>")]
    public string Text { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel();
        model.Text = "<Hello";
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }
}

View:

@model MyViewModel

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>

@using (Html.BeginForm())
{
    @Html.EditorFor(x => x.Text)
    @Html.ValidationMessageFor(x => x.Text)
    <button type="submit">OK</button>
}

Result:

enter image description here

Unobtrusive client side validation working fine.

3
  • what is jquery.validate.unobtrusive.js
    – Hogan
    May 25, 2012 at 7:21
  • It is a Microsoft script that interprets the HTML5 data-* attributes contained in the input fields (see OP's markup) and converts them into jquery.validate rules. Basically the data annotation attributes emit data-* attributes on the corresponding input fields and unobtrusive client side validation is performed on the client. It's the default model in ASP.NET MVC 3. May 25, 2012 at 7:24
  • Can you show me your HTML for that tag? It also validated properly for <>, but, because of the encoding, fails on l, g, and t for me (plus ;)
    – Andrew
    May 25, 2012 at 10:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.