5

I am trying using Email RegEx in javascript section in MVC4. But RegEx has @ char. It is not allowing to parse it

error:

Parser Error Message: "[" is not valid at the start of a code block.  
        Only identifiers, keywords, comments, "(" and "{" are valid.

code

@section scripts{
    <script type="text/javascript">
        $(document).ready(function() {

            $('#btnSave, #btnCoAuthor').click(function() {
                if (form.valid()) {
                    var hasError = false;
                    var emailReg = '[-0-9a-zA-Z.+_]+@[-0-9a-zA-Z.+_]+\.[a-zA-Z]{2,4}';
                      //Error showing @
James123
  • 11,184
  • 66
  • 189
  • 343

3 Answers3

14

You need to escape the @ for Razor, not for the JS string, itself. So, just use @@. Once Razor renders the HTML, it will end up as just an @.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • I get an error saying 'Parser Error Message: "@" is not valid at the start of a code block. Only identifiers, keywords, comments, "(" and "{" are valid.'. It's a pretty clean installation, any ideas for further debugging? Thanks – Sebi Jun 25 '19 at 10:31
3

Escaping with @@ works for me

var emailReg = '[-0-9a-zA-Z.+_]+@@[-0-9a-zA-Z.+_]+\.[a-zA-Z]{2,4}';

and output HTML is

var emailReg = '[-0-9a-zA-Z.+_]+@[-0-9a-zA-Z.+_]+\.[a-zA-Z]{2,4}';
Murali Murugesan
  • 22,423
  • 17
  • 73
  • 120
0

You could also use an escape sequence in JS, like:

var at = "\u0040";
Qtax
  • 33,241
  • 9
  • 83
  • 121