A simple email authentication code using HTML and JavaScript
Web applications use email authentication to confirm a user's identity by comparing the entered email address and password to user data that has been stored in the database. Here’s how an email authentication system might work in a web application:
- A form on the website is filled out by the user with their email address and password.
- When a user submits a form on the website, the server receives the data they entered.
- The user data that the server has stored is compared with the password and email. Typically, passwords are hashed for security purposes, and this data is kept in a database.
- The server considers a user to be authenticated if the password and email entered match the information that is stored.
- If the entered data doesn’t match, the server sends back an error message, which the website can display to the user.
I want to share some basic code in this blog post that demonstrates how to use HTML and JavaScript to implement this.
Step 1: Getting Started
Create a file named index.html. The following is the basic structure to get started:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Email Authentication</title>
</head>
<body>
</body>
</html>
Create a file named login.html to redirect to it when the entered details exist in the database. Make sure these two files exist in the same directory. Following is a sample code for the login page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Login</title>
</head>
<body>
<p>Welcome to login page</p>
</body>
</html>
Step 2: Designing the User Interface
First, include a <form> element in the <body> tag in order to collect the user’s email and password. Make sure to add the method = “post” attribute to specify that the data should be sent to the server using the HTTP POST method. By using this attribute, the data will not be visible in the URL.
<form method="post"> </form>
Inside the <form> element, add a label for an email input field using the <label> element and specify the input using the <input> element.
<label for="email">Email:</label>
<input type="email" id="email" name="email" />
<br />
In a similar way, add a label for a password input field using the <label> element and specify the input using the <input> element.
<label for="password">Password:</label>
<input type="password" id="password" name="password" />
<br />
Now add a button that submits the form when clicked.
<button type="submit" id="signIn">Sign In</button>
Here’s what your output should look like when you open the HTML file in the browser.
Now we need to place some <div> elements on the top of the email field, the bottom of the email field, and the bottom of the password field. You will understand why we should add them as we move on to JavaScript. But for now, just assume that there are elements that have no content.
Type this code above the email field.
<div id="error-message-sign-in" style="color: #fff200eb"></div>
Type this code below the email field.
<div id="error-message-email" style="color: red"></div>
Type this code below the password field.
<div id="error-message-password" style="color: red"></div>
Now this is just a User Interface (UI). To add functionality to this page, we need to add a JavaScript file using the <script> tag. Add this tag just above the <body /> tag, assuming index.js is the name of the JavaScript file.
<script src="./index.js"></script>
Finally, this is what your index.html code should look like
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Email Authentication</title>
</head>
<body>
<!-- Form for email authentication -->
<form method="post">
<!-- Error message for sign in -->
<div id="error-message-sign-in" style="color: #fff200eb"></div>
<label for="email">Email:</label>
<input type="email" id="email" name="email" />
<br />
<!-- Error message for email validation -->
<div id="error-message-email" style="color: red"></div>
<label for="password">Password:</label>
<input type="password" id="password" name="password" />
<br />
<!-- Error message for password validation -->
<div id="error-message-password" style="color: red"></div>
<button type="submit" id="signIn">Sign In</button>
</form>
<!-- JavaScript file for form validation -->
<script src="./index.js"></script>
</body>
</html>
Step 3: Adding Functionality
Following are the functionalities that I would like to add to this UI:
- When the user enters an invalid email address or just clicks the field and leaves it, an error message should appear right below the email field. An invalid email address means that the email entered has less than 5 characters.
- In a similar way, when the user enters an invalid password or just clicks the field and leaves it, an error message should appear right below the password field. An invalid password means that the password entered doesn’t lie between 4 and 60 characters.
- When the user clicks Sign In without entering data in the email field, password field, or both, I need to display the corresponding error messages.
- When the user enters valid details, but they are not present in the database, an error message should appear at the top.
Following are the outputs that we are going to achieve:
Create a file named index.js in the same directory as your index.html and login.html files. By using the getElementById() method, we can retrieve the reference to the email field, the password field, and the Sign In button.
// Get the email field's reference
const emailField = document.getElementById("email");
// Get the password field's reference
const passwordField = document.getElementById("password");
// Sign in button
const signInButton = document.getElementById("signIn");
Also, let us retrieve the references to the error message fields.
// Error message fields' references
const errorMessageEmail = document.getElementById("error-message-email");
const errorMessagePassword = document.getElementById("error-message-password");
const errorMessageSignIn = document.getElementById("error-message-sign-in");
Since this is a very simple demonstration, let us assume a database as a list of objects. Each object has an email and password as properties. You can add more objects if you want to
// Create a database of imaginary users
const imaginaryDatabase = [
{
email: "admin@gmail.com",
password: "Admin@123",
},
];
Now let us create a function handleEmailField to prevent the error messages from quickly disappearing when clicking on Sign In and check the conditions.
// Function to handle the email field
function handleEmailField(event) {
// Prevent the default behaviour of the form
event.preventDefault();
// Check if the email field is empty or has a length less than 5 characters
if (emailField.value.trim() === "" || emailField.value.length < 5) {
// Display the error message
errorMessageEmail.textContent = "Please enter a valid email address.";
} else {
errorMessageEmail.textContent = "";
}
}
Next, we will add event listeners to the email field for input and blur events. We add a listener to the input event because we need to dynamically change the error message when the user is typing in the email field. We add a listener for the blur event because when the user clicks and leaves the field, an error message should be displayed.
// Add event listener to the email field for input and blur events
emailField.addEventListener("input", handleEmailField);
emailField.addEventListener("blur", handleEmailField);
In a similar way, we will now create a function handlePasswordField and add event listeners to the password field.
// Function to handle the password field
function handlePasswordField(event) {
// Prevent the default behaviour of the form
event.preventDefault();
// Check if the password field is empty or has a length less than 4 characters and greater than 60 characters
if (
passwordField.value.trim() === "" ||
passwordField.value.length < 4 ||
passwordField.value.length > 60
) {
// Display the error message
errorMessagePassword.textContent =
"Your password must contain between 4 and 60 characters.";
} else {
errorMessagePassword.textContent = "";
}
}
// Add event listener to the password field for input and blur events
passwordField.addEventListener("input", handlePasswordField);
passwordField.addEventListener("blur", handlePasswordField);
Create a function handleSignIn to see if a user exists in the database and redirect to login.html, and if not, display an error message.
// Function to handle the sign in button
function handleSignIn(event) {
// Prevent the default behaviour of the form
event.preventDefault();
// Find the user in the database using the entered email
const user = imaginaryDatabase.find(
(user) => user.email === emailField.value
);
if (!user && emailField.value !== "" && passwordField.value !== "") {
errorMessageSignIn.textContent =
"Sorry, we can't find an account with this email address.";
return;
} else if (passwordField.value !== user.password) {
errorMessageSignIn.textContent = "Incorrect password.";
return;
} else {
// Redirect to login.html
window.location.href = "./login.html";
}
}
Finally, we need to add the three event listeners to the Sign In button because we need to handle cases where the user simply clicked Sign In without entering anything or left either of the fields blank and clicked the button.
// Add event listeners to the sign in button for click event
signInButton.addEventListener("click", handleSignIn);
signInButton.addEventListener("click", handleEmailField);
signInButton.addEventListener("click", handlePasswordField);
Live Website: https://vineethchivukula.github.io/emailAuth/