1

Closed

Encoded expressions for Regex validation

description

The expression defined using DataAnnotation in the server-side code is HTML encoded when rendered as an attribute, i.e. this:

[RegularExpression(@"^[^,<>\s@]+@([^\s,@\.\[\]]+\.)*[^\s,@\.\[\]]+\.[^\s,@\.\[\]]+$", ErrorMessage = "Invalid Email")]
public string EmailAddress { get; set; }

is rendered as:

data-val-regex-pattern="^[^,<>^[^,<>\s@]+@([^\s,@\.\[\]]+\.)*[^\s,@\.\[\]]+\.[^\s,@\.\[\]]+$" The result is an invalid validation expression.
Closed Aug 13, 2012 at 5:21 PM by HongmeiG
We cannot repro this issue. Please see discussion for details.

comments

BradWilson wrote Jun 13, 2012 at 7:38 PM

What is the manifestation of the problem?

Have you tried t repro this with the latest MVC nightly build?

_jimmys wrote Jun 14, 2012 at 9:48 AM

The result is that the validation fails. The above expression is from the code I debugged when I seen the issue.

If the JavaScript validates the expression in the encoded form

^[^,<>^[^,<>\s@]+@([^\s,@\.\[\]]+\.)*[^\s,@\.\[\]]+\.[^\s,@\.\[\]]+$ the following email would not be valid: test@server.com whilst in the original form

^[^,<>\s@]+@([^\s,@\.\[\]]+\.)*[^\s,@\.\[\]]+\.[^\s,@\.\[\]]+$ this email would be valid.

I have the fix already, we even exchanged emails about it, struggling with the git currently. See emails with Jimmy Skowronski :)

I will test it with the latest nightly build later today and post a result here.

_jimmys wrote Jun 14, 2012 at 12:49 PM

Just tested with the Unobtrusive.Validation.2.0.20614.0 and AspNet.Mvc.4.0.20614.0 and still having the same effect.

BradWilson wrote Jun 19, 2012 at 12:37 AM

I presume you're running in 4.5?

This looks like the new AntiXSS encoder, but it should be no problem that the URL is being encoded, because the value in JavaScript should not show the encoding.

_jimmys wrote Jun 19, 2012 at 2:00 PM

I've seen this of the first time in MVC 3. Tried with the latest build after you asked.

As far as I can see the JavaScript is getting the value of the attribute as it is. Fixed it myself by adding

params = $('<div/>').html(params).text();

in the

$jQval.addMethod("regex", function (value, element, params) {

but there may be better way (I'm sure there is).

BradWilson wrote Jun 20, 2012 at 3:52 PM

I write this in an HTML page:
<div data-val-regex-pattern="^[^,&lt;&gt;\s@]+@([^\s,@\.\[\]]+\.)*[^\s,@\.\[\]]+\.[^\s,@\.\[\]]+$" />
<script type="text/javascript" src="Scripts/jquery-1.7.2.js"></script>
<script type="text/javascript">
    $(function () {
        var $div = $("div"),
            data = $div.data("val-regex-pattern");

        alert(data);
    });
</script>

And the alert says:

Message from webpage

^[^,<>\s@]+@([^\s,@\.\[\]]+\.)*[^\s,@\.\[\]]+\.[^\s,@\.\[\]]+$

OK

So I don't see how the encoding could be affecting things, because as far as JavaScript is concerned, the transport encoding is not visible.