Search code examples
asp.net-mvchtmlemail

Use "@" in html5 input pattern attribute with MVC


Does anyone know how I can use a "@" within the pattern attribute on a HTML5 email input having a MVC page?

<input type="email" pattern="^[a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$">

At runtime I get this error:

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

When I use "data-pattern" instead of "pattern" I can escape it with "@@", but with "pattern" that fails too.

Thanks in advance :)


Solution

  • It can be done 2 ways:

    Render the "@" through razor:

    <input type="email" pattern="^[a-zA-Z0-9._+-]+@("@")[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$">
    

    With a HTML encode:

    <input type="email" pattern="^[a-zA-Z0-9._+-]+&#64;[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$">