OTP Input Field Using Bootstrap 5

OTP Input Field Using Bootstrap 5
Code Snippet:OTP Verify Mockup
Author: Marcus
Published: January 14, 2024
Last Updated: January 22, 2024
Downloads: 8,368
License: MIT
Edit Code online: View on CodePen
Read More

This code helps you to create an OTP input field using Bootstrap 5, allowing users to verify a code sent via email. The major functionality involves inputting a one-time password using six input fields and verifying it. It enables easy user interaction for code validation.

You can integrate this code into your website where OTP verification is needed, such as user registration, two-factor authentication, account recovery, payment confirmation, or secure access control. Moreover, you can customize the code to fit your specific requirements and design.

How to Create an OTP Input Field Using Bootstrap 5

1. First of all, add the Bootstrap 5 CSS file to the <head> section of your HTML file. This step ensures that the styling and layout of your OTP input field will be consistent with Bootstrap styles.

<link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css'>

2. Insert the following HTML code into the body of your HTML document. This code provides the structure for the OTP input field and the verification button.

<section class="container-fluid bg-body-tertiary d-block">
  <div class="row justify-content-center">
      <div class="col-12 col-md-6 col-lg-4" style="min-width: 500px;">
        <div class="card bg-white mb-5 mt-5 border-0" style="box-shadow: 0 12px 15px rgba(0, 0, 0, 0.02);">
          <div class="card-body p-5 text-center">
            <h4>Verify</h4>
            <p>Your code was sent to you via email</p>

            <div class="otp-field mb-4">
              <input type="number" />
              <input type="number" disabled />
              <input type="number" disabled />
              <input type="number" disabled />
              <input type="number" disabled />
              <input type="number" disabled />
            </div>

            <button class="btn btn-primary mb-3">
              Verify
            </button>

            <p class="resend text-muted mb-0">
              Didn't receive code? <a href="">Request again</a>
            </p>
          </div>
        </div>
      </div>
    </div>
</section>

3. Copy and paste the following CSS code into a <style> block in your HTML document or include it in an external CSS file. This CSS is responsible for styling the OTP input field.

.otp-field {
  flex-direction: row;
  column-gap: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.otp-field input {
  height: 45px;
  width: 42px;
  border-radius: 6px;
  outline: none;
  font-size: 1.125rem;
  text-align: center;
  border: 1px solid #ddd;
}
.otp-field input:focus {
  box-shadow: 0 1px 0 rgba(0, 0, 0, 0.1);
}
.otp-field input::-webkit-inner-spin-button,
.otp-field input::-webkit-outer-spin-button {
  display: none;
}

.resend {
  font-size: 12px;
}

.footer {
  position: absolute;
  bottom: 10px;
  right: 10px;
  color: black;
  font-size: 12px;
  text-align: right;
  font-family: monospace;
}

.footer a {
  color: black;
  text-decoration: none;
}

4. Finally, copy the following JavaScript code and include it in your HTML document, preferably just before the closing </body> tag. This JavaScript code handles user interactions with the OTP input field and enables the “Verify” button when a valid OTP is entered.

const inputs = document.querySelectorAll(".otp-field > input");
const button = document.querySelector(".btn");

window.addEventListener("load", () => inputs[0].focus());
button.setAttribute("disabled", "disabled");

inputs[0].addEventListener("paste", function (event) {
  event.preventDefault();

  const pastedValue = (event.clipboardData || window.clipboardData).getData(
    "text"
  );
  const otpLength = inputs.length;

  for (let i = 0; i < otpLength; i++) {
    if (i < pastedValue.length) {
      inputs[i].value = pastedValue[i];
      inputs[i].removeAttribute("disabled");
      inputs[i].focus;
    } else {
      inputs[i].value = ""; // Clear any remaining inputs
      inputs[i].focus;
    }
  }
});

inputs.forEach((input, index1) => {
  input.addEventListener("keyup", (e) => {
    const currentInput = input;
    const nextInput = input.nextElementSibling;
    const prevInput = input.previousElementSibling;

    if (currentInput.value.length > 1) {
      currentInput.value = "";
      return;
    }

    if (
      nextInput &&
      nextInput.hasAttribute("disabled") &&
      currentInput.value !== ""
    ) {
      nextInput.removeAttribute("disabled");
      nextInput.focus();
    }

    if (e.key === "Backspace") {
      inputs.forEach((input, index2) => {
        if (index1 <= index2 && prevInput) {
          input.setAttribute("disabled", true);
          input.value = "";
          prevInput.focus();
        }
      });
    }

    button.classList.remove("active");
    button.setAttribute("disabled", "disabled");

    const inputsNo = inputs.length;
    if (!inputs[inputsNo - 1].disabled && inputs[inputsNo - 1].value !== "") {
      button.classList.add("active");
      button.removeAttribute("disabled");

      return;
    }
  });
});

That’s all! hopefully, you have successfully created an OTP input field using Bootstrap 5. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X