OTP Input Box In Vue JS

Introduction:

A one-time password (OTP) or passcode is a sequence of letters and digits that serves as the user’s authentication for just one login or transaction. Each one-time password is generated by an algorithm that takes into account contextual data, such as time-based data or past login occurrences, to provide a unique value.

In this article, we use vue3-otp-input npm package to generate the OTP box in our Vue application. So, let’s start step by step to implement it.

Get started:

Step 1: Set up your Vue project.

Goto your desired folder location and run the following command to create a new Vue project.

vue create otp-input

It will take some time. After creating the project, change your directory by

cd otp-input

then running the following command to check project is successfully established or not.

npm run serve

Step 2: Install npm vue3-otp-input

npm i vue3-otp-input

Step 3: Add following HTML in the <template> tag.

Add the following code in HelloWorld.vue component or create a new one as your need.

<template>
  <div class="hello">
    <v-otp-input
      input-classes="otp-input"
      separator="-"
      :num-inputs="6"
      :should-auto-focus="true"
      :is-input-num="true"
      :placeholder="['*', '*', '*', '*', '*', '*']"
      @on-change="onChange"
      @on-complete="onComplete"
    />
  </div>
</template>

Step 4: Import the VOtpInput component in your component and add the following code in <script> tag.

<script>
import VOtpInput from 'vue3-otp-input';
export default {
  name: 'HelloWorld',
  components: {
    VOtpInput,
  },
  methods: {
    onChange(val) {
      console.log("changed", val)
    },
    onComplete(val) {
      console.log("Complete", val)
    }
  }
}
</script>

Step 5: Add style.

<style>
.hello {
  display: flex;
  justify-content: center;
}

.otp-input {
  width: 35px;
  height: 35px;
  padding: 5px;
  margin: 0 10px;
  font-size: 20px;
  border-radius: 4px;
  border: 1px solid rgba(0, 0, 0, 0.3);
  text-align: center;
}

.otp-input.is-complete {
  background-color: #e4e4e4;
}
.otp-input::-webkit-inner-spin-button,
.otp-input::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
input::placeholder {
  font-size: 15px;
  text-align: center;
  font-weight: 600;
}
</style>

Now, save everything and check the output on http://localhost:8080/

You can also find more details of events and methods of vue3-otp-input by clicking here.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories