Explain Codes LogoExplain Codes Logo

Why does HTML5 form-validation allow emails without a dot?

html
form-validation
regex-patterns
client-side-validation
Alex KataevbyAlex Kataev·Jan 13, 2025
TLDR

HTML5 form validation, specifically type="email", can be rather lenient, allowing emails like user@localhost. For enhanced validation, apply regex to the pattern attribute as such:

<input type="email" pattern=".+@.+\..+" title="Don't forget the '.' in the email domain, or you'll make the internet cry." />

This security guard ensures there's a dot in the domain area, keeping in line with conventional email formats. Custom pattern boosts the accuracy of form validation.

The quirkiness of email variations

Emails can come in various valid formats — some may surprise you. According to RFC 822, emails without a dot like user@localhost are technically valid, predominantly in private networks.

Boosting validation using pattern

You can improve the form's validation using the pattern attribute with type="email". To block addresses without a dot in the domain, use .+\..{2,}. This mandates a domain extension of at least two characters:

<input type="email" pattern=".+\..{2,}" title="A domain extension (like .com or .org) is required, unless you're living on Mars." />

In other words, it won't allow something as simplistic as a@b.

Regular expressions and their tricky corners

While stricter validation via regex seems helpful, be aware that overly strict regex could exclude valid email addresses. Since not all emails follow the [email protected] model, features like quoted strings and comments can make regex patterns complex.

Server-side validation: an extra security layer

While regex aids in client-side validation, server-side validation ensures more secure form submission. For instance, a client might not catch emails as a@b, despite them failing in actual email sending scenarios, underlining the need for server-side validation.

Detailing requirements using title

The title attribute can be used to offer users guidance about the required format of the input. This tooltip, showing the acceptable format, appears when a user hovers over the input or tries to submit a non-conforming value.

Required versus nice-to-have validation

While the required attribute is essential to prevent users from overlooking the field, add pattern for an additional nice-to-have validation stage before the form reaches your server.

Testing your validation process

Remember to carry out tests on your regex with sample emails, using resources like the Wikipedia page on email formats, or regex examples given by MDN. Ensuring the validation logic matches your requirements, you can even build more complex validation logic into your form with JavaScript.