Boone
Boone

Reputation: 1056

HTML5 pattern validation being ignored

I have an email input field that I have a regex of ^[^@]+@[^@.]+.[^@]+$, but when ran it is not requiring the .com.

Go to https://jsfiddle.net/uscktx9d/ and type in www@www and hit submit. This should fail validation but is not. As you can see here https://regex101.com/r/pB6iF4/1, the regex should be requiring the .com.

Why is my HTML5 not requiring this?

Upvotes: 3

Views: 2313

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627535

In a regex, a literal dot should be declared as an escaped \. symbol. See Special characters in regular expressions that should be escaped if you want to make sure they are treated as literals.

Also, HTML5 pattern attribute value is anchored by default, i.e. the whole pattern is wrapped into ^(?: and )$.

The regular expression language used for this attribute is the same as that used in JavaScript, except that the pattern attribute is matched against the entire value, not just any subset (somewhat as if it implied a ^(?: at the start of the pattern and a )$ at the end).

Thus, you just need to use

<input name="asdf" pattern="[^@]+@[^@.]+\.[^@]+" placeholder="email@example.com" title="email@example.com">

See updated fiddle

Upvotes: 1

Sam
Sam

Reputation: 20486

If you're going to use HTML5 input validation for an email, use type email. This will do native HTML5 validation for emails and have added benefits (like showing an @ symbol on mobile devices' virtual keyboards).

Also, remember that any frontend validation should be re-validated in the backend.

To answer your question, though, you need to escape . with a backslash.

Upvotes: 3

Related Questions