This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by aykacode
Email addresses are a critical part of online communication, and ensuring that the email addresses entered by users are valid is an important task for any web application. In this blog post, we will discuss how to use regular expressions in JavaScript to validate email addresses according to the rules specified in the official RFC 5322 standard.
First, let's take a look at the regular expression that we will use for validation:
const emailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
This regular expression may look daunting at first glance, but it is actually composed of several smaller, simpler regular expressions that are combined to form a complete email address validation pattern. Let's break it down:
/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@/
The first part of the regular expression matches the local part of the email address, which consists of the username and the domain name (e.g. john.doe in john.doe@example.com). This part of the regular expression allows the local part to contain letters, numbers, and a few special characters (., !, #, $, %, &, ', *, +, /, =, ?, ^, _, [backtick], {, |, }, ~, and -).
/@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?/
The next part of the regular expression matches the domain name of the email address (e.g.
example.com
injohn.doe@example.com
). This part of the regular expression allows the domain name to contain letters and numbers, and allows for the use of internationalized domain names (IDN) by allowing the use of hyphens (-
) within the domain name.
/(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
The final part of the regular expression matches the top-level domain (TLD) of the email address (e.g.
com
injohn.doe@example.com
). This part of the regular expression allows the TLD to contain letters and numbers, and allows for the use of IDN TLDs by allowing the use of hyphens (-
) within the TLD.
Now that we have a thorough understanding of the regular expression, let's see how we can use
This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by aykacode

aykacode | Sciencx (2022-12-15T22:04:08+00:00) Validating email addresses using regular expressions in JavaScript. Retrieved from https://www.scien.cx/2022/12/15/validating-email-addresses-using-regular-expressions-in-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.