Regular expressions, or regex for short, are powerful structures used for find matching patterns in strings. They exist in various programming languages and they are mostly used to validate credentials such as email addresses, phone numbers, URLs and more.
So, In this article, we will discuss how to write a regex for email validation.
Build A Regular Expression For Email
Before writing a regex, it is important to analyze the structure of targeted pattern. In this case, this pattern, of course, is an email. An email address consists of two parts, the local part and the domain part, separated by an '@' symbol.
- The local part can contain alphanumeric characters, dots and some special characters
- The domain part can contain alphanumeric characters and dots.
By considering parts listed above, here's an example of regex for email validation:
/^[^\s@]+@[^\s@]+\.[^\s@]+$/
Let's break down this regex pattern:
- "/" - start of regex pattern
- "^" - start of string
- "\s" - space characters
- "@"- match the '@' symbol
- [^\s@]+ - match one or more characters that are not whitespace or '@'
- "+" - one or more characters that match the character class.
- "." - match the dot character itself
- "[^\s@]+.[^\s@]+" - match one or more characters that are not whitespace or '@', followed by a dot, followed by one or more characters that are not whitespace or '@'
- "$" - end of string
- "/" - end of regex pattern
This regex pattern validates an email address that meets the following requirements:
- The local part must contain one or more characters that are not whitespace or '@'
- The domain part must contain one or more characters that are not whitespace or '@', followed by a dot, followed by one or more characters that are not whitespace or '@'
How To Validate Email With Regex In Javascript
After writing a regex for validation, it can be used with a programing language. So, let's see how we can use this regex pattern in JavaScript to validate an email address:
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
function validateEmail(email) {
return emailRegex.test(email);
}
console.log(validateEmail('[email protected]')); // true
console.log(validateEmail('invalidemail')); // false
In this example, we define a regex pattern for email validation and a function validateEmail that takes an email address as input and returns true if it matches the regex pattern and false otherwise. We then test this function with two email addresses, one that is valid and one that is not.
Conclusion
In conclusion, regex patterns can be used to validate email addresses by defining the pattern for the local and domain parts. By using regex for email validation, we can ensure that user input is formatted correctly and prevent invalid input from being submitted in our javascript applications.
Thank you for reading.