Giter VIP home page Giter VIP logo

vue3-otp-input's Introduction

vue3-otp-input

Vue 3 OTP Input is a 5.0 KB fully customizable OTP (one-time password) input component for OTPs, transaction pins, and passwords built with Vue 3.x and Vue Composition API..

πŸ“Ή Demo

Gifphy

βš™οΈ Installation

Install as package

You can install vue3-otp-input via the terminal.

pnpm i vue3-otp-input

OR

Install via CDN

<script src="https://unpkg.com/vue3-otp-input"></script>

<script src="https://cdn.jsdelivr.net/npm/vue3-otp-input"></script>

πŸ“– Usage Demo

1/3. Register as a Vue component locally OR

<script setup lang="ts">
import { ref } from "vue";
import VOtpInput from "vue3-otp-input";

const otpInput = ref<InstanceType<typeof VOtpInput> | null>(null);
const bindModal = ref("");

const handleOnComplete = (value: string) => {
  console.log("OTP completed: ", value);
};

const handleOnChange = (value: string) => {
  console.log("OTP changed: ", value);
};

const clearInput = () => {
  otpInput.value?.clearInput();
};

const fillInput = (value: string) => {
  console.log(value);
  otpInput.value?.fillInput(value);
};
</script>

1/3. Register as a Vue component globally

//  main.js or main.ts
import { createApp } from 'vue'
import App from './App.vue'

import VOtpInput from "vue3-otp-input";

const app = createApp(App)

app.component('v-otp-input', VOtpInput).mount('#app')

2/3. Use the registered component in your Vue template

<template>
    <div style="display: flex; flex-direction: row">
      <v-otp-input
        ref="otpInput"
        input-classes="otp-input"
        :conditionalClass="['one', 'two', 'three', 'four']"
        separator="-"
        inputType="letter-numeric"
        :num-inputs="4"
        v-model:value="bindValue"
        :should-auto-focus="true"
        :should-focus-order="true"
        @on-change="handleOnChange"
        @on-complete="handleOnComplete"
        :placeholder="['*', '*', '*', '*']"
      />
    </div>
    <button @click="clearInput()">Clear Input</button>
    <button @click="fillInput('2929')">Fill Input</button>
</template>

3/3 [Optional]. Some basic styling options

This css has to go into a <style> tag which does not have scoped attributed

<style>
.otp-input {
  width: 40px;
  height: 40px;
  padding: 5px;
  margin: 0 10px;
  font-size: 20px;
  border-radius: 4px;
  border: 1px solid rgba(0, 0, 0, 0.3);
  text-align: center;
}
/* Background colour of an input field with value */
.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>

πŸ” Props

Name
Type Required Default Description
value string false "" v-modal:value for bind dynamic value
num-inputs number true 4 Number of OTP inputs to be rendered.
separator component
false Provide a custom separator between inputs by passing a component. For instance, <span>-</span> would add - between each input
input-classes className (string) false none Style applied or class passed to each input.
input-type string false "tel" Input type. Optional value: "password", "number", "tel", "letter-numeric".
inputmode string false "numeric" This allows a browser to display an appropriate virtual keyboard. Optional value: "numeric", "text", "tel". [Learn More](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/inputmode)
should-auto-focus boolean false false Auto focuses input on inital page load.
should-focus-order boolean false false Auto correct the input order. See #39
placeholder array false [] Specify an expected value for each input. Example: :placeholder="['*', '*', '*', '*']". The length of this array should be equal to num-inputs.
conditionalClass array false [] Specify a class to be applied to each input based on the value of the input. Example: :conditionalClass="['one', 'two', 'three', 'four']". The length of this array should be equal to num-inputs.
is-disabled boolean false false Disables all the input fields.

🀺 Methods

Name
Description
clearInput() Use with ref for clearing all otp inputs, see code example section.
fillInput() Use with ref for fill otp inputs. The value should be same length as `numInputs` length. See code example section.

🐴 Events

Name
Description
on-change Return OTP code was changing when we made a change in inputs.
on-complete Return OTP code typed in inputs.

🀟🏽 License

MIT

πŸ““ Contributing

Contributions are always welcome!

See contributing.md for ways to get started.

Please adhere to this project's code of conduct.

🧸 Appendix

This component is a rewite of vue-otp-input component to support Vue 3.x. Feel free to use it in your project, report bugs and make PR πŸ‘πŸ½.

vue3-otp-input's People

Contributors

ejirocodes avatar gemerz avatar gerolmed avatar mini-ghost avatar nimaebra avatar thatonecalculator avatar victorybiz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

vue3-otp-input's Issues

`SingleOtpInput` pattern should change based on the `input-type` prop

Describe the bug
The Pattern of the SingleOtpInput should change based on the input-type prop. letter-numeric should allow a-zA-Z as well.

To Reproduce
Make a component with input-type letter-numeric` and type a OTP code that includes letters. The input will become invalid.
See: https://github.com/bachdgvn/vue-otp-input/blob/develop/src/components/SingleOtpInput.vue#L10

Expected behavior
The letter-numeric should allow the pattern 0-9a-zA-Z.

image

Methods for inserting values programmatically

Hello Ejiro,
Thank you for making this component.

In my application I would like to be able to use a virtual keyboard with which the OTP is entered. But this would require methods to update the OTP programmatically, like updateCurrentFocusValue(3) or maybe updateValueAt(0, 3).

Edit: Closing this for now because I've taken a different route in my project

How to install and start the project

Describe the bug
When I run npm install it produces the following error

npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR! 
npm ERR! While resolving: @vue/[email protected]
npm ERR! Found: @vue/[email protected]
npm ERR! node_modules/@vue/cli-service
npm ERR!   dev @vue/cli-service@"^5.0.8" from the root project
npm ERR!   peer @vue/cli-service@"^3.0.0 || ^4.0.0 || ^5.0.0-0" from @vue/[email protected]
npm ERR!   node_modules/@vue/cli-plugin-babel
npm ERR!     dev @vue/cli-plugin-babel@"^5.0.8" from the root project
npm ERR!   3 more (@vue/cli-plugin-router, @vue/cli-plugin-typescript, @vue/cli-plugin-vuex)
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer @vue/cli-service@"^3.0.0 || ^4.0.0-0" from @vue/[email protected]
npm ERR! node_modules/@vue/cli-plugin-unit-jest
npm ERR!   dev @vue/cli-plugin-unit-jest@"~4.5.19" from the root project
npm ERR! 
npm ERR! Conflicting peer dependency: @vue/[email protected]
npm ERR! node_modules/@vue/cli-service
npm ERR!   peer @vue/cli-service@"^3.0.0 || ^4.0.0-0" from @vue/[email protected]
npm ERR!   node_modules/@vue/cli-plugin-unit-jest
npm ERR!     dev @vue/cli-plugin-unit-jest@"~4.5.19" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR! 
npm ERR! See /Users/ci-alex.liu/.npm/eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/ci-alex.liu/.npm/_logs/2024-03-08T14_50_44_082Z-debug-0.log

To Reproduce
Steps to reproduce the behavior:

  1. clone this project
  2. run npm install

Desktop (please complete the following information):



otpInput.value.clearInput() does not clear the very last num input field

I am using the otpInput as below:

<v-otp-input ref="otpInput" inputmode="numeric" separator="" :num-inputs="6" :should-auto-focus="false" :is-input-num="true" :placeholder="['', '', '', '', '', '']" @on-complete="handleOnComplete" />

But when I call otpInput.value.clearInput() in the handleOnComplete() it clears only the first 5 inputs but not the last one.

Not sure if I am doing something wrong or if this a something that happens:

image

Just want to be able to clear it in case the user needs a new code resent.

Also I am not finding how to programmatically focus the first input when required, tried otpInput.value.focus() but it didn't work. Say when the OTP code has been sent to the user.

otpInput.value.focusInput(0) goes to the 2nd input:

image

Is this an issue or working as expected?
Any help appreciated.

Provide a prop to assign a class name to the main container

I want to apply styles to main container of input divs shown below. Currently there is no way to provide a class name to the main div. Can only style each individual inputs.

image

A prop to provide a class name for the main container would solve this problem.

For now, I'm using an attribute name to target the main container (works for my specific scenario).

div[is-input-num='true'] {
    justify-content: space-between;
}

When user start typing from right to left it is duplicating the value when using v-model

Describe the bug
When user start typing from right to left, it is duplicating the value and also autfocus is not working as expected

To Reproduce
Steps to reproduce the behavior:

Instead of going from left to right. I tried going from right to left.
suppose i have 6 input fields and i directly typed in 6th field. it is duplicating the value in first too.

for 5th it is duplicating the value in 2nd.

Expected behavior
should not duplicate values

Set optional value to handleOnBlur

Hi there

I'm trying to implement this nice component on a project. The problem I'm facing is that my inputs are coming from a virtual component keyboard, so when I click on one of my buttons on the virtual keyboard this function is triggered.
const handleOnBlur = () => { activeInput.value = -1; };
So the otp input is never filled. I'm wondering if this onblur behavior can be optional for cases like this?

Also I'm facing that I have to call method pin.value.handleOnChange(value); to fill the inputs from this virtual keyboard. Maybe we can expose this method as a prop in the component like the @on-complete.

Support for v-model is not provided

Problem: With current version I'm not able to set value.
Solution: value prop along with input event can be provided to support v-model

Also make development experience great.

Security Mode

Props

secure boolean false Display * instead of character

Feature: show/view functionality when using `input-type="password"`

Is your feature request related to a problem? Please describe.
Sometimes a user wants to see the input.
It would be nice to have a method to hide/show the input.

Describe the solution you'd like
I.e. when using input-type="password" to offer a method which toggles inputs between type="text" and type="password".

We could create a PR if this is wanted.

[Help] Styling issue

Hi, thanks for maintaining this component.

I just import this component inside my vue file, but the page display as follow:

Untitled

I following the code example that you wrote in the readme, beside that, I purposely set the height and width to 1px, the component don't have any effect. Can you please guide me how to resolve the box sizing issue?

FYI, I imported your component in my quasar framework project. Is that possible your component styling will crash with the framework? Any advice will be appreciated, thank you again πŸ˜„

Cannot be imported

got the following error
` App β€’ ERROR β€’ UI in ./src/pages/Index.vue?vue&type=script&lang=js

Module not found: Can't resolve imported dependency "vue3-otp-input"
Did you forget to install it? You can run: yarn add vue3-otp-input

App β€’ COMPILATION FAILED β€’ Please check the log above for details.`

Vue 3 and Vite Build Resolve Error

Versions:

    "vue": "^3.2.24",
    "vite": "^2.7.6",
    "vite-plugin-environment": "^1.1.0",
    "vite-plugin-eslint": "^1.3.0",
    "vite-svg-loader": "^3.1.1"

When I import otp component in vue file, my development is giving this error

$ vite --host --https
 > node_modules/vite/dist/node/chunks/dep-fcec4469.js:30629:10: error: [plugin: vite:dep-scan] Failed to resolve entry for package "vue3-otp-input". The package may have incorrect main/module/exports specified in its package.json: Failed to resolve entry for package "vue3-otp-input". The package may have incorrect main/module/exports specified in its package.json.
    30629 β”‚     throw new Error(`Failed to resolve entry for package "${id}". ` +
          β•΅           ^
    at packageEntryFailure (/home/bixos/Projects/royal/royal-front/node_modules/vite/dist/node/chunks/dep-fcec4469.js:30629:11)
    at resolvePackageEntry (/home/bixos/Projects/royal/royal-front/node_modules/vite/dist/node/chunks/dep-fcec4469.js:30625:9)
    at tryNodeResolve (/home/bixos/Projects/royal/royal-front/node_modules/vite/dist/node/chunks/dep-fcec4469.js:30440:20)
    at Context.resolveId (/home/bixos/Projects/royal/royal-front/node_modules/vite/dist/node/chunks/dep-fcec4469.js:30257:28)
    at Object.resolveId (/home/bixos/Projects/royal/royal-front/node_modules/vite/dist/node/chunks/dep-fcec4469.js:42784:55)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async resolve (/home/bixos/Projects/royal/royal-front/node_modules/vite/dist/node/chunks/dep-fcec4469.js:42987:26)
    at async /home/bixos/Projects/royal/royal-front/node_modules/vite/dist/node/chunks/dep-fcec4469.js:43125:34
    at async callback (/home/bixos/Projects/royal/royal-front/node_modules/esbuild/lib/main.js:832:28)
    at async handleRequest (/home/bixos/Projects/royal/royal-front/node_modules/esbuild/lib/main.js:664:30)

   node_modules/vite/dist/node/chunks/dep-fcec4469.js:43115:18: note: This error came from the "onResolve" callback registered here
    43115 β”‚             build.onResolve({
          β•΅                   ~~~~~~~~~
    at setup (/home/bixos/Projects/royal/royal-front/node_modules/vite/dist/node/chunks/dep-fcec4469.js:43115:19)
    at handlePlugins (/home/bixos/Projects/royal/royal-front/node_modules/esbuild/lib/main.js:756:23)
    at Object.buildOrServe (/home/bixos/Projects/royal/royal-front/node_modules/esbuild/lib/main.js:1044:7)
    at /home/bixos/Projects/royal/royal-front/node_modules/esbuild/lib/main.js:1895:17
    at new Promise (<anonymous>)
    at Object.build (/home/bixos/Projects/royal/royal-front/node_modules/esbuild/lib/main.js:1894:14)
    at Object.build (/home/bixos/Projects/royal/royal-front/node_modules/esbuild/lib/main.js:1749:51)
    at /home/bixos/Projects/royal/royal-front/node_modules/vite/dist/node/chunks/dep-fcec4469.js:42945:54
    at Array.map (<anonymous>)

   local-script:/home/bixos/Projects/royal/royal-front/src/components/account/wallet/WithdrawItem.vue:3:22: note: The plugin "vite:dep-scan" was triggered by this import
        3 β”‚ import VOtpInput from 'vue3-otp-input';
          β•΅                       ~~~~~~~~~~~~~~~~

error when starting dev server:
Error: Build failed with 1 error:
node_modules/vite/dist/node/chunks/dep-fcec4469.js:30629:10: error: [plugin: vite:dep-scan] Failed to resolve entry for package "vue3-otp-input". The package may have incorrect main/module/exports specified in its package.json: Failed to resolve entry for package "vue3-otp-input". The package may have incorrect main/module/exports specified in its package.json.
    at failureErrorWithLog (/home/bixos/Projects/royal/royal-front/node_modules/esbuild/lib/main.js:1493:15)
    at /home/bixos/Projects/royal/royal-front/node_modules/esbuild/lib/main.js:1151:28
    at runOnEndCallbacks (/home/bixos/Projects/royal/royal-front/node_modules/esbuild/lib/main.js:941:63)
    at buildResponseToResult (/home/bixos/Projects/royal/royal-front/node_modules/esbuild/lib/main.js:1149:7)
    at /home/bixos/Projects/royal/royal-front/node_modules/esbuild/lib/main.js:1258:14
    at /home/bixos/Projects/royal/royal-front/node_modules/esbuild/lib/main.js:629:9
    at handleIncomingPacket (/home/bixos/Projects/royal/royal-front/node_modules/esbuild/lib/main.js:726:9)
    at Socket.readFromStdout (/home/bixos/Projects/royal/royal-front/node_modules/esbuild/lib/main.js:596:7)
    at Socket.emit (events.js:314:20)
    at addChunk (_stream_readable.js:297:12)

input onchanged class

Hello

I would like to add a class to the input when a number is entered in this input. For example, I want to add a bounce class so that a digit input has a ripple effect when the digit is added.

Could you add such a parameter?

Maintenance

1 year since the last commit. Is this package still maintained? Are there good alternatives out there?

Pre-fill inputs

Hello is it possible to pre-fill the inputs?

Perhaps v-model ?

copy paste issue

hey there
seems like copy pasting values not reflected on model
so onComplete and onChange are not firing when pasting otp value

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.