Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :)

like image 726
Dirk Pennings Avatar asked May 10 '13 06:05

Dirk Pennings


People also ask

What is the use of pattern attribute in input elements of html5?

The pattern attribute specifies a regular expression that the <input> element's value is checked against on form submission.

What is the use of pattern attribute in HTML form?

The pattern attribute specifies a regular expression the form control's value should match. If a non- null value doesn't conform to the constraints set by the pattern value, the ValidityState object's read-only patternMismatch property will be true.

How are input validation patterns used?

The pattern attribute of the <input> element allows you to add basic data validation without resorting to JavaScript. It works by matching the input value against a regular expression. A regular expression is a formalized string of characters that define a pattern.

Can we use regex in HTML?

While arbitrary HTML with only a regex is impossible, it's sometimes appropriate to use them for parsing a limited, known set of HTML. If you have a small set of HTML pages that you want to scrape data from and then stuff into a database, regexes might work fine.


1 Answers

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}$">
like image 77
Dirk Pennings Avatar answered Sep 27 '22 17:09

Dirk Pennings