regex validate email

Regex Validating Email

Regex stands for Regular Expression, which is a sequence of characters that forms a search pattern to match within a string. In the case of validating email, we can use regex to ensure that the format of the email follows a specific pattern, which includes:

  • An email address must have only one "@" symbol.
  • The "@" symbol must be followed by a domain name.
  • The domain name must consist of at least one period ".".
  • The domain name must have at least two characters after the last period ".".

To achieve this, we can use the following regular expression:


/^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$/
  

This regular expression is divided into three parts:

  1. The first part, (^([a-zA-Z0-9_\-\.]+)), matches the username before the "@" symbol. It allows letters, numbers, underscores, hyphens, and periods in the username.
  2. The second part, (@([a-zA-Z0-9_\-\.]+)), matches the "@" symbol and the domain name. It allows letters, numbers, underscores, hyphens, and periods in the domain name.
  3. The third part, (\.([a-zA-Z]{2,5})$), matches the period "." and the top-level domain. It allows letters between two to five characters only.

We can use the test() method in JavaScript to test if an email is valid or not using the regular expression we created. Here is an example:


let email = "[email protected]";
let regex = /^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$/;
let isValidEmail = regex.test(email);

console.log(isValidEmail); // true
  

Another way to validate an email address is to use the built-in HTML5 validation. You can use the "type" attribute on the input element with a value of "email". This will automatically validate the input as an email address:


<form action="#" method="post">
  <label for="email">Email:</label>
  <input type="email" id="email" name="email" required>
  <input type="submit" value="Submit">
</form>
  

This will display an error message if the email address entered is not valid. However, this method may not work in all browsers, so it's always a good idea to have a backup method for validation.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe