JavaScript

6-Digit OTP Verification System for Web Security

How to generate 6 digit One Time Password and verify using JavaScript only

7/29/2024
0 views

Security on websites is an essential part of this decade. You can add various kinds of security features on your website - OTP is one of them. Using simple JavaScript you can generate OTP and verify. Here, I created a 6-digit OTP verification system using HTML, CSS and JavaScript only.

Step 1: HTML Setup

<section>
<aside>
<button id="genBtn" onclick="generateOTP()">Generate OTP</button>
<div id="otp"></div>
<div id="otpInput">
<input type="text" maxlength="1" />
<input type="text" maxlength="1" />
<input type="text" maxlength="1" />
<input type="text" maxlength="1" />
<input type="text" maxlength="1" />
<input type="text" maxlength="1" />
</div>
</aside>
</section>

Step 2: CSS Styling

section aside button {
cursor: pointer;
background-color: var(--green);
color: var(--white);
border: none;
padding: 6px 15px;
font-size: 20px;
border-radius: 5px;
}

section aside button:disabled {
background-color: var(--lightGray);
color: var(--ash);
}

#otp {
margin: 25px 0;
height: 30px;
font-size: 25px;
color: var(--white);
}

#otpInput {
display: flex;
justify-content: center;
gap: 10px;
}

#otpInput input {
padding: 10px;
text-align: center;
font-size: 30px;
border-radius: 8px;
border: 2px solid transparent;
width: 20px;
outline: none;
background-color: var(--gray);
color: var(--white);
}

#otpInput input:focus {
border-color: var(--green);
color: var(--green);
}

#otpInput input:disabled {
background-color: var(--lightGray);
color: var(--ash);
}

Step 3: Generate OTP

function generateOTP() {
btn.disabled = true;
otp = Math.floor(Math.random() * (999999 - 100000) + 100000).toString();
otpView.innerText = otp;
}

Step 4: Verification by Typing OTP

function typeOTP($event) {
const input = $event.target;
const value = input.value;
const fldIndex = +input.dataset.index;

if ($event.key === "Backspace" && fldIndex > 0) {
input.previousElementSibling.focus();
}

if (checkNumber(value)) {
if (value.length > 0 && fldIndex < inputs.length - 1) {
input.nextElementSibling.focus();
}

if (input.value !== "" && fldIndex === inputs.length - 1) {
submit();
}
} else {
clear($event);
}
}

Step 5: Verification by Pasting OTP

function pasteOTP($event) {
const data = $event.clipboardData.getData("text");
const value = data.replace(/ /g, "").split("");
if (value.length === inputs.length) {
inputs.forEach((input, index) => {
input.value = value[index];
});
submit();
}
}

Generate OTPOTP verificationWeb Security

Related Examples