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 it in a JavaScript function to validate email addresses.
First, we will define a function called validateEmail
that takes an email address as an argument:
function validateEmail(email) {
// Validation code goes here
}
Get 40% off premium Skillshare membership
Next, we will use the test
method of the emailRegex
regular expression to check if the email address passed to the function is a valid email address according to the pattern defined in the regular expression:
function validateEmail(email) {
return emailRegex.test(email);
}
Finally, we can use the validateEmail
function to check if a given email address is valid by passing it as an argument to the function:
let email = 'john.doe@example.com';
if (validateEmail(email)) {
console.log('Valid email address');
} else {
console.log('Invalid email address');
}
That's it! With just a few lines of code, we have implemented a reliable email address validation function using regular expressions in JavaScript. As always, it's important to keep in mind that while this method is effective, it is not foolproof and should be used in conjunction with other validation techniques to ensure the security and reliability of your web application.
At the end of this blog post, I want to thank all of my readers for following along and for their support. I'm grateful for the opportunity to share my knowledge and experiences with you, and I hope that my posts have been helpful and informative.
If you are a self-taught full-stack developer, you should read my ebook. It will guide you on your journey and provide you with a clear and "real" path to success:
The Self-Taught Full Stack Web Developer's Journey: A Comprehensive Guide to SuccessFinally, don't forget to follow me on Twitter for updates on new blog posts and other interesting content. Thanks again for your support and I look forward to continuing to share my knowledge with you.
Top comments (4)
While it's true that the
<input type="email">
HTML element does provide basic email address validation, it may not be sufficient for all use cases. Using regular expressions (regex) to validate email addresses allows for more precise and customizable validation, as you can specify exactly what constitutes a valid email address according to your specific requirements.Additionally, the
<input type="email">
element only works on modern browsers, whereas regex can be used to validate email addresses on any platform.That being said, using both the
<input type="email">
element and regex can provide an extra layer of validation to ensure that the email addresses entered by users are in the correct format.Good response!
<input type="email">
is good for modern navigators, but not for all. This is important to check in backend and/or on front to check if it is an email with a ReGex. 👍🏼☕While this will probably be fine for all email addresses, it is not conformant with RFC 5322.
It doesn't account for folded white space, comment folded white space, or comments. (which are allowed in both the local part and the domain).
This, according to RFC 5322, is a valid email address:
I don't think your regex will capture that.
Some resources about validating emails using regexp
html.spec.whatwg.org/multipage/inp...
stackoverflow.com/questions/201323...