Email Validation in JavaScript

quiz
Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Overview

JavaScript is a modern and widely accepted language that is loved by many developers. Why does everyone love JavaScript? Because it is one of the most popular languages that is used to create Full-Stack applications that have both the Frontend and the Backend and is also used to create beautifully designed web pages.

Apart from creating websites and making them look cool, JavaScript also helps in many ways. It improves the user experience on the website by providing some necessary features like Form Validation in Javascript.

Form Validation in Javascript means JavaScript applies some checks to the form data at the time of entering data so that the wrong type of data is not sent to the server and errors occur.

Scope

In this article you will learn about:

  • What is Validation
  • What are Regular Expressions
  • How to do Email Validation with JavaScript with and without Regular Expressions
  • Examples showing different types of email validations.

What is validation?

Validation is a process that makes sure that the data that the user has entered into a form is of the correct type. Simply put, It is the process of checking the values inputted by the user. This is done on the client-side, and its purpose is to save time for the server.

For example, Let's suppose there is a form on a page where you have to enter your phone number. The phone number has some rules that it should be of 10 digits (in India), and it should only have numerals and no other characters. So, we can use JavaScript to check these things before sending data to the server. This will help the user to catch errors and also save the server time. Also, the user will get an immediate response about any errors.

How does Email Validation work in JavaScript

To understand how email validation work first we have to understand what an Email is: An email is a string of ASCII characters (alphabets, numerals, special characters, etc.) which is separated into two parts by the @ (at) symbol.

  • First part - personal information
  • Second part - domain name at which the email is registered.

Personal information can contain:

  • 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.

Domain name contains:

  • Letters
  • Digits
  • Hyphens
  • Dots

Now that we know what an email consists of, we can now learn the ways we use it for validation.

  • Using Regular Expressions - This is the preferred way as it provides more flexibility and reduces the chances of error.
  • Without Regular Expressions - This is a simpler method but less flexible

Let's learn about both ways.

A regular expression is a sequence of characters that specifies a search pattern in the text. Let's look at a code example to see how RegEx can be used for validation.

First, we have to make an HTML form, and we will link a JavaScript file to it.

<!DOCTYPE html>
<html>
  <body>
    <div>
      <h3 class="h3">Enter your email address</h3>
      <form name="form1" action="#">
        <input type="text" name="text1" />
        <br />
        <input
          type="submit"
          name="submit"
          value="Submit"
          onclick="validateEmail(document.form1.text1)"
        />
      </form>
    </div>
    <script src="email-validation.js"></script>
  </body>
</html>

Now we have to write the JavaScript code using Regular Expressions that will validate the emails.

Here are some of the simple steps that you have to follow:

First, we make a variable that will store regular expression literal, which consists of a pattern enclosed between slashes: const myRegEx = /ab+c/; After this, we use the match() to match the values of the inputted text with the pattern that we have created. There are also other functions that can be used with regular expressions like exec(), test(), matchAll(), search(), replace(), split().

Examples

Simple Email Validation Check

function validateEmail(inputText) {
  var mailFormat =  /\S+@\S+\.\S+/;
  if (inputText.value.match(mailFormat)) {
    alert("Valid address!");
    return true;
  } else {
    alert("Invalid address!");
    return false;
  }
}

Output

Simple Email Validation

Simple Email Validation Example

Email Validation with characters, digits, special characters, @, and dot

function validateEmail(inputText) {
  var mailFormat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
  if (inputText.value.match(mailFormat)) {
    alert("Valid address!");
    return true;
  } else {
    alert("Invalid address!");
    return false;
  }
}

Output

Validation with char

Validation with special char

Email Validation with @ and dot.

This we can do without the use of Regular Expressions

function validateEmail(inputText) {
  var data = inputText.value;
    var atSign = data.indexOf("@");
    var dotSign = data.indexOf(".");
  if (atSign<1 || dotSign<atSign+2 || dotSign+2>=data.length) {
    alert("Please add @ and .!");
    return false;
  }
}

Output

Validation with dot

Email Validation with Alphabets, Numbers, and Special Characters

function validateEmail(inputText) {
  var mailFormat = /^[A-Za-z0-9 ]+$/;
  if (inputText.value.match(mailFormat)) {
    alert("Special Characters Not Found!");
    return true;
  } else {
    alert("Special Characters Found!");
    return false;
  }
}

Output

Validation with alpha

Validation with nums

Regular Expressions may look very scary and like someone has written complete garbage at first look, but if you understand them, then they can help you in many ways.

If you want to learn more about regex, then here are some resources.

Conclusion

  • Form Validation in Javascript on a website improves user experience and makes the website more attractive.
  • Validation is the process of checking the data inputted by the user against some rules.
  • Form Validation in Javascript is preferred on the client-side as it saves the server time.
  • For validating an Email with JavaScript, we use Regular Expressions.
  • Regular Expression is a sequence of characters that specifies a search pattern in the text.
Challenge Time!
quiz
quiz
Time to test your skills and win rewards! Note: Rewards will be credited after the next product update.
Free Courses by top Scaler instructors
rcbGet a Free personalized Career Roadmap from