How to Do an Email Validation in JavaScript?

JavaScript is an open-source programming language. It is designed for creating web-centric applications. It is lightweight and interpreted, which makes it much faster than other languages. JavaScript is used to create beautifully designed web applications.

Email validation in JavaScript is an important part of the user experience of a web application. Validation assists in inputting forms and makes sure that only valid information is passed to the server from the client-side of the application.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

What is Validation?

Validation is commonly defined as the process of checking the values inputted by the user. It plays an important role in web applications and enhances the overall user experience. We can validate email, password, date, mobile numbers, and many other fields.

JavaScript is used to validate the form data on the client-side of a web application, and this speeds up the validation process because of faster data processing when compared with server-side validation.

Now that we know a bit about validation, let’s go ahead and implement email validation in JavaScript.

How to validate email using JavaScript

Email validation is a critical part of validating an HTML form. An email is a string or a subset of ASCII characters separated into two parts by @ symbol. The first part contains personal information while the other contains the domain name at which the email is registered.

The personal information part can contain the following ASCII characters:

  • Uppercase and lowercase letters (A-Z and a-z)
  • Numeric characters (0-9)
  • Special characters - ! # $ % & ' * + - / = ? ^ _ ` { | } ~
  • Period, dot, or full stop (.) with the condition that it cannot be the first or last letter of the email and cannot repeat one after another.

Master Core Java 8 Concepts, Java Servlet & More!

Java Certification TrainingENROLL NOW
Master Core Java 8 Concepts, Java Servlet & More!

The domain name contains:

  • Letters
  • Digits
  • Hyphens
  • Dots

One of the most popular ways of validating email in JavaScript is by using regular expressions. JavaScript uses regular expressions to describe a pattern of characters. 

email.js

This file contains the JavaScript code that we need for email validation. We are using regular expressions to validate the email at the client-side of a web application.

function ValidateEmail(input) {

  var validRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;

  if (input.value.match(validRegex)) {

    alert("Valid email address!");

    document.form1.text1.focus();

    return true;

  } else {

    alert("Invalid email address!");

    document.form1.text1.focus();

    return false;

  }

}

  • Define a regular expression for validating email address
  • Check if the input value matches with regular expression
  • If it does match, send an alert stating “valid email address”
  • If it doesn’t match, send an alert stating “invalid email address”

email.html

This file contains the base HTML code that has all the elements defined for this webpage.

<!DOCTYPE html>

<html lang="en">

  <head>

    <meta charset="utf-8" />

    <title>JavaScript Email Validation</title>

    <link rel="stylesheet" href="email.css" type="text/css" />

  </head>

  <body onload="document.form1.text1.focus()">

    <div class="mail">

      <h2>Input an email address</h2>

      <form name="form1" action="#">

        <ul>

          <li><input type="text" name="text1" /></li>

          <li>&nbsp;</li>

          <li class="validate">

            <input

              type="submit"

              name="validate"

              value="Validate"

              onclick="ValidateEmail(document.form1.text1)"

            />

          </li>

          <li>&nbsp;</li>

        </ul>

      </form>

    </div>

    <script src="email.js"></script>

  </body>

</html>

Related Reading: What is HTML (Hyper Text Markup Language)?

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

email.css

This file contains the CSS styles that are needed for styling the HTML elements in the webpage. The styles are self-explanatory and you are free to change these styles according to your preference.

li {

  list-style-type: none;

  font-size: 16pt;

}

.mail {

  margin: auto;

  padding-top: 10px;

  padding-bottom: 10px;

  width: 400px;

  background: teal;

  border: 1px soild silver;

}

.mail h2 {

  margin-left: 38px;

  color: white;

}

input {

  font-size: 20pt;

}

input:focus,

textarea:focus {

  background-color: lightyellow;

}

input validate {

  font-size: 12pt;

}

.rq {

  color: #ff0000;

  font-size: 10pt;

}

Output

The output should look and feel like this in the end.

email-validation

Fig: Email Validation in JavaScript

We hope you understood how to implement email validation in JavaScript after going through this article. This is a relatively simple topic that gets used in various kinds of web applications.

Learn email validation in JavaScript to enhance your JavaScript skills. Our Java Course provides detailed instruction on email validation, ensuring competence in designing reliable, user-friendly forms for web application development and coding skills.

Related Reading: The Ultimate CSS Tutorial for Beginners

Get Ahead of the Curve and Master JavaScript Today

Are you wondering how you can gain the skills necessary to take advantage of JavaScript’s immense popularity now that you are familiar with email validation? We have got your back! We offer a comprehensive Java Certification Training, which will help you become career-ready upon completion. Also email validation is one of the commonly asked topics in the Java interview questions. So, get started today and seize your future!

If you’re an aspiring web and mobile developer, Java Certification Training will broaden your skills and career horizons.

Do you have any questions for us? Please mention it in the comments section of this ‘Email Validation in JavaScript’ article and we'll have our experts answer it for you.

FAQs

1) What is validation for an email?

Email validation is a process to check if an email address is correctly formatted and follows the standard rules for email addresses.

2) How to validate an email with regex?

Use this regex pattern: /^[\w\.-]+@[a-zA-Z\d\.-]+\.[a-zA-Z]{2,}$/ 

3) How do I validate email format?

You can validate the format using regular expressions (regex) or use built-in email validation functions in programming languages.

4) How to validate email in JavaScript without regex?

You can use the built-in HTML5 input element with type="email" or use the email input validation in JavaScript.

5) What is the regex code for email validation in JavaScript?

The regex code for email validation in JavaScript is:
/^[\w\.-]+@[a-zA-Z\d\.-]+\.[a-zA-Z]{2,}$/

About the Author

Taha SufiyanTaha Sufiyan

Taha is a Research Analyst at Simplilearn. He is passionate about building great user interfaces and keeps himself updated on the world of Artificial Intelligence. Taha is also interested in gaming and photography.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.