How to Validate Email Address without using Regular Expression in JavaScript ?
Last Updated :
01 Aug, 2024
Email validation in JavaScript is the process of ensuring that an email address entered by the user is in the correct format and is a valid email address or not. This is typically done on the client side using JavaScript before the form is submitted to the server.
An email address must have the following components to be considered valid:
- Username: It is the unique address that appears before the @ symbol. The username can contain letters, numbers, and certain special characters (e.g., ., _, -).
- @ symbol: It separates the username from the domain name.
- Domain name: It is the part of the email address that appears after the @ symbol. The domain name can contain letters, numbers, and certain special characters. The domain name must contain at least one period (.) to separate the different levels of the domains. For example - geeksforgeeks.org has two levels: geeksforgeeks and org).
- Top-level domain: It is the part of the domain name that appears after the last period (For example - .com, .edu, .gov).
Additionally, there are some conventions and additional rules for email addresses, such as:
- Some domain names may have subdomains (For example - write.geeksforgeeks.org)
- Email addresses are case-insensitive, meaning the characters can be in upper or lower case.
- Some special characters like "+" or "_" are allowed.
Approach: Using String methods
Email validation in JavaScript on the client side can be done without using regular expressions by using a combination of string methods and logical conditions to check if the email address entered by the user is in the correct format.
This code checks if the "@" symbol is present in the email address by looking for its position using the indexOf() method. If the "@" symbol is not present or it is the first character of the email address, the method returns false, indicating that the email address is invalid.
The lastIndexOf() method is used to find the last occurrence of the "." character in the email address. If the "." character is not present if it appears before the "@" symbol or if it is the last character of the email address, this method returns false indicating the email address is invalid.
- Email Validation Function:
- The JavaScript function
validateEmailAddress
checks the validity of an email address without using regular expressions. - It utilizes basic string manipulation and comparison methods to validate the email format.
- Key Validation Checks:
- The function checks the presence and position of the "@" symbol (
atSymbol
). - It verifies the presence and position of the last "." symbol (
dotSymbol
). - It ensures that "@" is not at the beginning and "." is not at the beginning or immediately after "@".
- It confirms that there is at least one character between "@" and ".".
- It checks that there is at least one character after the last "." symbol.
- It ensures there are no spaces in the email address.
- Alert Messages:
- If the email address passes all validation checks, an alert with "Email address is valid" is displayed.
- If any of the checks fail, an alert with "Error !!! Email address is not valid" is displayed.
- Form Submission:
- The form includes an
onSubmit
attribute, calling the validateEmailAddress
function when the form is submitted. - The function returns
true
if the email is valid, allow the form submission, and false
otherwise, preventing the form from being submitted.
- HTML Form:
- The HTML form includes a text input for the email address and a submit button.
- It captures the email address input and triggers the validation function on form submission.
If all of the above conditions are met, the email address is considered to be valid and the validation passes.
Example: In this example, we will implement the above approach.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Validate Email Address</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.container {
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
width: 300px;
text-align: center;
}
h1 {
font-size: 24px;
margin-bottom: 20px;
}
input[type="text"] {
width: 100%;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type="submit"] {
width: 100%;
padding: 10px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #45a049;
}
.alert {
margin-top: 10px;
padding: 10px;
color: white;
border-radius: 4px;
display: none;
}
.alert.success {
background-color: #4CAF50;
}
.alert.error {
background-color: #f44336;
}
</style>
<script type="text/javascript">
// JavaScript code for email validation without using regular expression
function validateEmailAddress(emailAddress) {
let atSymbol = emailAddress.indexOf("@");
let dotSymbol = emailAddress.lastIndexOf(".");
let spaceSymbol = emailAddress.indexOf(" ");
let doubleDotSymbol = emailAddress.indexOf("..");
let alertBox = document.getElementById("alert");
if ((atSymbol != -1) &&
(atSymbol != 0) &&
(dotSymbol != -1) &&
(dotSymbol != 0) &&
(dotSymbol > atSymbol + 1) &&
(emailAddress.length > dotSymbol + 1) &&
(spaceSymbol == -1) &&
(doubleDotSymbol == -1)) {
alertBox.textContent = "Email address is valid.";
alertBox.className = "alert success";
alertBox.style.display = "block";
return true;
} else {
alertBox.textContent = "Error! Email address is not valid.";
alertBox.className = "alert error";
alertBox.style.display = "block";
return false;
}
}
function handleSubmit(event) {
event.preventDefault(); // Prevent form submission
let email = document.forms["theForm"]["email_address"].value;
validateEmailAddress(email);
}
</script>
</head>
<body>
<div class="container">
<h1>Email Validation</h1>
<form name="theForm" onsubmit="handleSubmit(event)">
Email address: <input type="text" name="email_address"
placeholder="Enter your email address">
<input type="submit" value="Submit form">
</form>
<div id="alert" class="alert"></div>
</div>
</body>
</html>
Output:
Similar Reads
How to Validate Email Address using RegExp in JavaScript? Validating an email address in JavaScript is essential for ensuring that users input a correctly formatted email. Regular expressions (RegExp) provide an effective and efficient way to check the email format.Why Validate Email Addresses?Validating email addresses is important for a number of reasons
3 min read
JavaScript - How to Validate Form Using Regular Expression? To validate a form in JavaScript, you can use Regular Expressions (RegExp) to ensure that user input follows the correct format. In this article, we'll explore how to validate common form fields such as email, phone number, and password using RegExp patterns.1. Validating an Email AddressOne of the
4 min read
How to check for IP address using regular expression in javascript? The task is to validate the IP address of both IPv4 as well as IPv6. Here we are going to use RegExp to solve the problem. Approach 1: RegExp: Which split the IP address on. (dot) and check for each element whether they are valid or not(0-255). Example 1: This example uses the approach discussed abo
2 min read
How to Determine if a value is Regular Expression using Lodash? When working with dynamic data in JavaScript, it's often necessary to validate the types of values, including checking whether a value is a regular expression (RegExp). Lodash provides an elegant and easy-to-use utility function for this: _.isRegExp. This function allows us to verify if a given valu
2 min read
Regular Expression to Validate a Bitcoin Address BITCOIN is a digital currency. During the digital currency transaction, a BTC address is required to verify the legality of a bitcoin wallet a Bitcoin address is a long set of alphanumeric characters that contains numbers and letters. A Bitcoin address indicates the source or destination of a Bitcoi
6 min read
How to Validate Data using express-validator Module in Node.js ? Validation in node.js can be easily done by using the express-validator module. This module is popular for data validation. There are other modules available in market like hapi/joi, etc but express-validator is widely used and popular among them.Steps to install express-validator module:Â Â You can
3 min read
JavaScript - How to Create Regular Expression Only Accept Special Formula? To ensure that a string matches a specific formula or pattern, you can use a regular expression (RegExp) in JavaScript. Here are the various ways to create a regular expression that only accepts regular formulas.1: Alphanumeric Code FormulaLet's create a regular expression that matches a formula lik
3 min read
How to Validate an Input is Alphanumeric or not using JavaScript? To validate alphanumeric in JavaScript, regular expressions can be used to check if an input contains only letters and numbers. This ensures that the input is free from special characters.Approach: Using RegExpA RegExp is used to validate the input.RegExp is used to check the string of invalid chara
1 min read
How to check if email address is already in use or not using express-validator in Node.js ? The registration or Sign Up in any website always requires a username. Most of the time we use 'email' to register on a website. The registration email is always unique and must refer to only one user otherwise conflict between the users can happen. To solve this conflict every website must have the
5 min read
How to Validate Decimal Numbers in JavaScript ? Validating user input is an essential aspect of Web Development. As a developer, when we are playing with the numeric inputs provided by the end-user, it is quite important to ensure that the input provided by the user is in the correct format. We can use the regular expression to Validate Decimal N
2 min read