20

I am performing email address validation with javascript in a razor view page. The regex I am going to use is similar to the one proposed at Validate email address in JavaScript?

However, because the regex contains an '@' character, I am getting parser error when try to run the web app.

my regex looks like

/^...otherpart @* ... other part$/

I tried to add an '@' character to make the in the origin regex ... @@* ..., this eliminated the compilation error but seems to make the regex stops working. (we have used it in another web app that does not use razor engine, so I know it works).

Is there any other way to escape the '@' character?

Community
  • 1
  • 1
Wei Ma
  • 3,125
  • 6
  • 44
  • 72
  • Have you tried wrapping your script block with ``? – Jasen Oct 18 '13 at 03:28
  • @Jasen I have not tried the trick. Will try tomorrow and let you know the result. – Wei Ma Oct 18 '13 at 03:32
  • If you use this script is several places it's probably a good idea to put it in it's own .js file. Individual validation rules, such as max/min, could be put in data- attributes for elements and read via jQuery. – jfrankcarr Oct 18 '13 at 03:48
  • 1
    @Jasen,@jfankcarr. I have taken your advise and used a separate file and everything is working now. Thanks! – Wei Ma Oct 18 '13 at 17:43

4 Answers4

27

You can add another @ in front of it to escape @@, try leaving out the quantifer *. If this doesn't seem to work then add <text></text> around the function, it tells Razor to not parse the contents. Alternatively you can put Javascript in a separate file to accomplish your needs.

If for some reason you have multiple @@ in your string, place code blocks ahead @:@@

hwnd
  • 69,796
  • 4
  • 95
  • 132
  • 1
    I've tried a few things... `` and beginning the line with `@:` but only `@@` appears to do the trick. The other option is to use a separate file. – Jasen Oct 18 '13 at 03:52
  • 2
    I would be inclined to put all of that into a separate file instead of writing a funky regex pattern to satisfy the Razor parser. Sometimes it's hard enough understanding a regex pattern without having to think about escaped characters. – Jasen Oct 18 '13 at 04:07
15

Put the following inside the regEx instead of @:

@('@')

The above will be rendered to a single @.

Your example will become:

/^...otherpart @('@')* ... other part$/
Shadi Alnamrouti
  • 11,796
  • 4
  • 56
  • 54
  • This should be the accepted answer! Doubling up the @@ changes your REGEX and that's not what you want. still, I wish there were a better way to scape the @ sign in razor, something like \@ – Kemuel Sanchez Nov 16 '17 at 12:35
0

Simply just use double @@.
It works for me and I think that is the only way.

Alexander Stepaniuk
  • 6,217
  • 4
  • 31
  • 48
keyone2693
  • 619
  • 1
  • 4
  • 17
0

It's better to use @('@') instead of @@ (not working for me). Example

<input class="form-control" pattern="^[a-zA-Z@('@')]{5,20}$"/>
Ghebrehiywet
  • 884
  • 3
  • 12
  • 20