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="^[^\&lt;\&gt;]*$"
data-val-regex="May not contain &lt;,&gt;" .../>
Edit:
- Because of the encoding, it was also catching
<>, but also tripping up on words with: tlike timglike 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:
- Disable asp.net input sanity checks on one page and check that in the action only
- Find a complex regex to match 3+ unicode ranges +/- dashes & numbers – .net + js compat.
- Write a custom regex validator that doesn’t have client side validation
- 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?
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
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:
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()inGlobal.asax.cs