Unlock Security: OTP Generator with Email Verification using JavaScript

Unlock Security: OTP Generator with Email Verification using JavaScript

How to Implement an OTP Generator with Email Verification

Introduction to OTP Generation

  • The video introduces the concept of implementing an OTP (One-Time Password) generator with email verification using HTML, CSS, and JavaScript.
  • Emphasis is placed on the importance of safeguarding applications and protecting user data through robust authentication methods.

Demo Overview

  • A demonstration shows the OTP verification window where users can enter their email address. The "Next" button is initially disabled until a valid email is entered.
  • After entering a valid email, clicking "Next" sends an OTP to that address. Users are prompted to check their email for a four-digit code.
  • If the user enters an invalid OTP, an error message appears, indicating that they need to input a valid code.

Project Setup

  • The presenter introduces themselves as Sharathchandar K and encourages viewers to subscribe for more tutorials. They have created a project folder named "OTP generator and email verification."
  • The project files include index.html, style.css, and script.js. An HTML boilerplate has been set up in index.html.

Building the HTML Structure

  • Inside index.html, a container div is created using Visual Studio Code's abbreviation feature. This includes headings for OTP verification instructions.
  • Additional elements such as input fields for the user's email address and explanatory text about receiving an OTP via email are added.

Live Server Functionality

  • The presenter demonstrates how to use the "Go Live" extension in Visual Studio Code to view changes in real-time on a browser.

Form Elements Creation

  • An input box for entering the user's email ID is added within a new div class called "form group."
  • A button labeled "Next" is also included, which will trigger sending the OTP when clicked.

Styling with CSS

  • In style.css, global styles are applied including resetting margins/padding and setting font family to Poppins.
  • Styles are defined for body elements: background color set to blue, minimum height adjusted, and flexbox properties used for centering content.

Container Styling

  • Specific styles are applied to the container class: white background color, width of 400px, border radius of 5px, padding adjustments, and centered text alignment.

Styling Input Forms and Buttons

Adding Styles to Input Boxes

  • The input box is styled with a height of 50px, width of 100%, font size of 15px, padding of 15px, border radius of 5px, no outline, and a light gray border.
  • A button is styled using an element selector with a width of 100%, height of 45px, pointer cursor, font size of 16px, blue background color, border radius of 30px, no border, white text color, and a bottom margin of 20px.

Creating Multiple Containers

  • Three container boxes are created by copying the initial container twice. Each container is labeled as step1, step2, and step3 for clarity.
  • The second container is modified to focus on OTP verification instead of email entry. It informs users that a one-time password has been sent to their email.

Implementing OTP Verification

  • An email address span tag is added within the OTP verification message to dynamically display the user's email.
  • The form group for entering the email is replaced with an OTP form containing instructions for entering a four-digit code sent via email.

Designing Input Fields for OTP

  • Four input boxes are created for the four-digit code using an abbreviation tool. These inputs are set up without specific IDs or names.
  • The button text changes from "Next" to "Verify," and additional messaging prompts users who did not receive their code to try again.

Finalizing Third Container Design

  • The third container displays a congratulatory message upon successful OTP verification along with an image indicating success.
  • CSS styles are applied to ensure proper layout and aesthetics across all containers. This includes setting margins and colors appropriately.

Enhancing User Experience with Styles

  • Flexbox properties are used in the OTP group to align input fields in a single line while maintaining spacing between them.
  • Additional styles disable spin buttons on number inputs by utilizing webkit appearance settings. This enhances user experience by providing cleaner input fields.

JavaScript Functionality Implementation

How to Access and Manipulate DOM Elements in JavaScript

Accessing HTML Elements

  • The process begins with declaring constants for each step using const, starting with step1 which accesses the document object representing the webpage.
  • The DOM tree structure is explained, showing how to access elements by class names for step2 and step3.
  • To retrieve an email address, the method document.getElementById is used since it requires an ID rather than a class.

Handling Input Fields

  • All input fields within a specific form can be accessed using document.querySelectorAll, allowing manipulation of multiple elements at once.
  • Constants are declared for buttons (nextButton and verifyButton) using their respective class selectors.

Event Listeners and Initial Setup

  • An event listener is added to the window's load event to display only the first form initially, hiding other containers by setting their display style to none.
  • Both buttons are disabled upon loading by adding a 'disabled' class, preventing user interaction until conditions are met.

Styling Disabled Buttons

  • CSS styles are applied to visually indicate that buttons are disabled, including changes in opacity and background color.
  • Pointer events are also disabled on these buttons to prevent any click actions while they remain inactive.

Email Validation Logic

  • A function named validateEmail is created utilizing regex patterns to check if an email format is valid. If valid, it enables the next button; otherwise, it keeps it disabled.
  • The validation function is triggered on keyup events in the input field where users enter their email addresses.

Sending Emails Using EmailJS

Email Service Setup and OTP Generation Process

Connecting to Email Account

  • The process begins by connecting to a Gmail account, which is essential for sending emails through the service created.
  • Users are prompted to create an email template that includes necessary fields such as subject, content, sender name, and reply-to address.

Creating the Email Template

  • An example email template is provided: "Dear Sir/Madam, you got a new message from [sender's name]. Please use this following OTP password to complete your login. Do not share this OTP with anyone."
  • To send emails using EmailJS, a CDN link must be added in the index.html file for proper initialization of the email object.

Initializing EmailJS Service

  • After adding the CDN link, the service ID needs to be initialized in script.js, allowing access to various email prototypes.
  • A click event listener is set up on a button that triggers OTP generation and verification processes.

Sending Emails with Parameters

  • The script requires additional parameters: service ID and template ID. These are defined as constants within the code.
  • A public key from EmailJS is needed for initialization; it allows sending templates via specified parameters like sender name and OTP.

Handling Template Parameters

  • Template parameters include values such as sender name (initially empty), OTP (empty), message (empty), and reply-to address (also initially empty).
  • If required fields are left empty when attempting to send an email, errors will occur. For instance, if the reply-to field is empty, an error indicating that the recipient address is missing will appear.

Finalizing Email Content

  • Once all fields are filled correctly (e.g., sender name updated), users can successfully send emails containing attachments or messages.

Generating a Four-Digit OTP

OTP Generation Logic

  • The function generateOTP utilizes Math.floor and Math.random to create a four-digit OTP. It generates random numbers between 1,000 and 9,999, ensuring the output is always four digits.
  • Removing the constant addition of 1,000 can lead to three-digit outputs. This highlights the importance of maintaining a minimum value for consistent OTP length.

Email Notification Process

  • After generating the OTP, an email is sent with a status response of 200. The email contains instructions and the generated OTP for user login.
  • The email includes a warning not to share the OTP and provides details about how many emails have been sent and remaining quota per day.

User Interface Enhancements

  • Changes are made to the UI elements such as buttons and text during the sending process. A loading animation indicates that an email is being sent.
  • Upon sending an email, UI elements are updated to reflect progress by changing display styles for different steps in the process.

Input Validation Mechanism

  • An event listener for keyup events restricts input fields to one character each. This ensures users cannot enter more than one digit per box when entering their OTP.
  • If all input boxes are filled correctly, a verification button becomes enabled, allowing users to proceed with confirming their entered OTP.

Verification Process

  • When clicking verify, all input values are concatenated into a single string for comparison against the generated OTP. Console logs help track user inputs during this process.

OTP Verification and Animation Implementation

Implementing OTP Verification Logic

  • The process begins with verifying the OTP (One-Time Password). If the entered OTP matches the expected value, the system proceeds to the next container. An error shake animation is triggered if it does not match.
  • Keyframes for a shake animation are defined in CSS, specifying margin changes at different percentages (0%, 25%, 75%, and 100%) to create a shaking effect when validation fails.

Handling Incorrect OTP Entries

  • A timeout function is implemented to remove the error shake class after one second, allowing for repeated attempts without persistent visual errors.
  • When entering an incorrect OTP multiple times, debugging reveals that the expected value may not be received correctly from email notifications.

Email Notification and Validation Process

  • The user checks their email inbox for received OTPs. Adjustments are made in code to ensure proper display settings for elements related to verification feedback.
  • A fade-in animation is added to enhance user experience when displaying messages or containers upon successful actions.

Functionality Enhancements

  • A new function is created in JavaScript to handle email changes effectively. This function modifies display properties of various elements based on user interactions.
  • The newly created function is initialized through HTML attributes, ensuring that clicking "try again" resets the interface appropriately.

Final Testing and User Experience Improvements