The validateEmail
function takes an email address as input and returns true
if the email matches the regex pattern, indicating a valid email format, or false
otherwise.
The common regex pitfalls and how to avoid them
As said, regex isn’t bulletproof, unless you make it a mile-long, attempting to cover all edge cases. So, check what to keep in mind:
- Complexity: Email address standards are complex, and no regex can validate every possible valid email address. For instance, the official specification allows for quoted strings and comments in email addresses, which are rarely used and often not considered in regex patterns.
- Performance: Overly complex regex patterns can be slow and inefficient, especially when processing large volumes of data.
- Readability: Complex regex patterns can be difficult to read and maintain, making it hard to understand what is being validated.
How to avoid the pitfalls?
- [Suggested] Consider using built-in validation functions or third-party libraries for more complex validation needs, as they may handle edge cases and performance issues. You can jump on lib validation and server-side validation by clicking on these links.
- Stick to simple and well-understood patterns for most use cases, understanding that some edge cases will be missed.
- Test the regex thoroughly with a wide range of email addresses to ensure it meets your specific needs.
Tip: regexp
can be used to define more specialized filters, note that it’s not common in email validation.
Email validation in HTML using JavaScript
Email validation within an HTML form helps ensure data integrity and enhances user experience.
Real-time feedback within modern web apps guides users to correct errors immediately, rather than after form submission. It helps avoid user frustration that might lead to form abandonment.
This immediate feedback implementation can be achieved by listening to user input events and validating them on the fly.
I’ll be using the oninput
or onchange
HTML event attributes trigger real-time email validation functions.
oninput
event triggers every time the user types or deletes something in the input field, providing immediate feedback. onchange
event triggers after the element loses focus, which is useful for final validation before submission.
In this JavaScript tutorial, I’ll use the oninput
event trigger and integrate regex-based validation. It’s a simple doctype html registration form without form name, textarea
, CSS styles, div
class, li
class, etc. Nonetheless, if you add them the address validation logic is still the same.
Check the steps below:
- Create a basic HTML form with an email input field: