Regular expression for email validation in Javascript

Regular expression for email validation in Javascript

Email validation is an important part of web development since it guarantees that the data your application gets is correct and in the desired format. Regular expressions (regex) is a javascript feature that helps us in the validation of the user mail.

Email validation is an important feature of any website which helps protect the website by allowing the valid and verified user to use the email.

Email validation using Javascript

An email is a string (a subset of ASCII characters) divided into two halves by the @ sign. The first part of the email contains the user information and the other part contains the domain name. The personal_info section can have up to 64 characters and the domain name can have up to 253 characters.

The Anatomy of an Email Address

Before we go into regular expressions, let’s go over the fundamentals of an email address. An email address is usually made up of two parts:

  1. Local Part: The part of the email address preceding the “@” symbol. It can include letters, numerals, and special characters such as dots (. ), underscores (_), and hyphens (-).
  2. Domain section: The section of the email address after the “@” symbol that defines the domain of the email server. It can contain letters, numerals, dots (. ), and hyphens (-). It may also have subdomains separated by dots.

Here are some of the examples of valid email address:
1. [email protected]
[email protected]
3. [email protected]

Examples of Invalid email addresses:

1.cosw.gmail.com
[email protected]
[email protected]

Using Regular Expressions for Email Validation

Regular expressions are built into JavaScript, making it quite easy to validate email addresses. Here’s a simple regular expression to get you started:

const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;

Let’s have a look at this regular expression in detail:

  • ‘^’and’$’are anchors that ensure the regex matches the entire string from start to end.
  • ‘[a-zA-Z0-9._-]+’ matches one or more characters, which can be letters, numerals, dots, underscores, or hyphens. This is the local portion of the email.
  • @ matches the “@” symbol.
  • [a-zA-Z0-9.-]+ matches one or more characters, which may be letters, digits, dots, or hyphens. This is the domain portion.
  • “.” corresponds to the dot (.) separating the domain from the top-level domain (TLD).
  • “[a-zA-Z]2,4” fits the TLD, which consists of two to four alphabetic characters.

When writing JavaScript, you may use the following regular expression to verify email addresses:

<div>
  <form action="#" id="form">
    <div class="input-box">
      <input type="text" name="" id="email" placeholder="Enter Email Address" onkeydown="validation()">
      <span id="text"></span>
    </div>
  </form>
</div>
Regular expression for email validation in Javascript
* {
  margin: 0;
  padding: 0;
  font-family: 'Poppins', sans-serif;
}

body {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: #373737;
}

#form {
  position: relative;
}

#form #email {
  width: 300px;
  background: #292929;
  outline: none;
  border: none;
  padding: 10px;
  border-radius: 6px;
  color: #fff;
  font-style: 18px;
}

#form .input-box {
  position: relative;
}

#text {
  display: block;
  color: #000;
  font-weight: 300;
  font-style: italic;
  padding: 5px;
}

#form.invalid .input-box::before {
  content: '';
  position: absolute;
  right: 12px;
  top: 9px;
  width: 24px;
  height: 24px;
  background: url(https://fadzrinmadu.github.io/hosted-assets/email-validation-check-using-javascript/invalid.png);
  -webkit-background-size: cover;
  background-size: cover;
}

#form.valid .input-box::before {
  content: '';
  position: absolute;
  right: 12px;
  top: 9px;
  width: 24px;
  height: 24px;
  background: url(https://fadzrinmadu.github.io/hosted-assets/email-validation-check-using-javascript/valid.png);
  -webkit-background-size: cover;
  background-size: cover;
}
Regular expression for email validation in Javascript
function validation() {
  let form = document.getElementById('form')
  let email = document.getElementById('email').value
  let text = document.getElementById('text')
  let pattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/

  if (email.match(pattern)) {
    form.classList.add('valid')
    form.classList.remove('invalid')
    text.innerHTML = "Your Email Address in valid"
    text.style.color = '#00ff00'
  } else {
    form.classList.remove('valid')
    form.classList.add('invalid')
    text.innerHTML = "Please Enter Valid Email Address"
    text.style.color = '#ff0000'
  }

  if (email == '') {
    form.classList.remove('valid')
    form.classList.remove('invalid')
    text.innerHTML = ""
    text.style.color = '#00ff00'
  }
}

The JavaScript function validation() checks if the entered email in a form matches a basic email pattern. If the email format is according to the defined pattern then a green line around the email box will appear showing a verified email and if the email id is not in the correct format then a red line across the email box displays an invalid email address.
If the email input is empty, it clears any styles and messages. This function provides real-time feedback on email validity to the user.

Email Validation Flow Chart

Email validation flow chart

Conclusion

For email validation, JavaScript’s regular expressions are effective tools. You can enhance data input quality in your web apps by comprehending the structure of email addresses and employing regular expressions correctly. However, to ensure a reliable and secure solution, combine email validation with server-side checks. This makes sure that email addresses are legitimate and deliverable as well as accurately formatted.

If you find this Blog helpful, then make sure to search Codewithrandom on Google for Front End Projects with Source codes and make sure to Follow the Code with Random Instagram page.



Leave a Reply