Skip to content

OTP Field ​

A one-time password input with one slot for each character.

Enter the 6-character code we sent to your device.

vue
<script setup lang="ts">
import { useId } from 'vue';
import { OTPField } from '@vase-ui/vue/otp-field';
import styles from './index.module.css';

const OTP_LENGTH = 6;

const id = useId();
const labelId = `${id}-label`;
const descriptionId = `${id}-description`;
</script>

<template>
  <div :class="styles.Field">
    <label :id="labelId" :for="id" :class="styles.Label">Verification code</label>
    <OTPField.Root
      :id="id"
      :aria-labelledby="labelId"
      :length="OTP_LENGTH"
      :aria-describedby="descriptionId"
      :class="styles.Root"
    >
      <OTPField.Input
        v-for="index in OTP_LENGTH"
        :key="index"
        :class="styles.Input"
        :aria-label="index === 1 ? undefined : `Character ${index} of ${OTP_LENGTH}`"
      />
    </OTPField.Root>
    <p :id="descriptionId" :class="styles.Description">
      Enter the 6-character code we sent to your device.
    </p>
  </div>
</template>
css
.Field {
  display: flex;
  flex-direction: column;
  align-items: start;
  gap: 0.25rem;
  width: 100%;
  max-width: 20rem;
}

.Label {
  font-size: 0.875rem;
  line-height: 1.25rem;
  font-weight: 700;
  color: oklch(14.5% 0 0deg);

  @media (prefers-color-scheme: dark) {
    color: white;
  }
}

.Root {
  display: flex;
  gap: 0.5rem;
  width: 100%;
}

.Input {
  box-sizing: border-box;
  margin: 0;
  padding: 0;

  border: 1px solid oklch(14.5% 0 0deg);
  width: 2.5rem;
  height: 2.5rem;
  border-radius: 0;
  font-family: inherit;
  font-size: 1rem;
  line-height: 1.5rem;
  font-weight: 400;
  text-align: center;
  background-color: white;
  color: oklch(14.5% 0 0deg);

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
  }

  &:focus {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}

.Description {
  margin: 0;
  font-size: 0.875rem;
  line-height: 1.25rem;
  color: oklch(43.9% 0 0deg);

  @media (prefers-color-scheme: dark) {
    color: oklch(70.8% 0 0deg);
  }
}
vue
<script setup lang="ts">
import { useId } from 'vue';
import { OTPField } from '@vase-ui/vue/otp-field';

const OTP_LENGTH = 6;

const id = useId();
const labelId = `${id}-label`;
const descriptionId = `${id}-description`;
</script>

<template>
  <div class="flex w-full max-w-80 flex-col items-start gap-1">
    <label :id="labelId" :for="id" class="text-sm font-bold text-neutral-950 dark:text-white"
      >Verification code</label
    >
    <OTPField.Root
      :id="id"
      :aria-labelledby="labelId"
      :length="OTP_LENGTH"
      :aria-describedby="descriptionId"
      class="flex w-full gap-2"
    >
      <OTPField.Input
        v-for="index in OTP_LENGTH"
        :key="index"
        class="m-0 h-10 w-10 rounded-none border border-neutral-950 bg-white dark:bg-neutral-950 text-center font-inherit text-base font-normal text-neutral-950 focus:outline-2 focus:-outline-offset-1 focus:outline-neutral-950 dark:focus:outline-white dark:border-white dark:text-white"
        :aria-label="index === 1 ? undefined : `Character ${index} of ${OTP_LENGTH}`"
      />
    </OTPField.Root>
    <p :id="descriptionId" class="m-0 text-sm text-neutral-600 dark:text-neutral-400">
      Enter the 6-character code we sent to your device.
    </p>
  </div>
</template>

Usage guidelines ​

  • Form controls must have an accessible name: Give the field a <label> element and name the group with it, or put the field in a Field. See Labeling an OTP field and the forms guide.

Anatomy ​

Import the component and assemble its parts:

vue
<script setup lang="ts">
import { OTPField } from '@vase-ui/vue/otp-field';
</script>

<template>
  <OTPField.Root :length="1">
    <OTPField.Input />
    <OTPField.Separator />
  </OTPField.Root>
</template>

Examples ​

Labeling an OTP field ​

A native <label> names the first input when its for is the id of OTPField.Root. To name the group too, give the label an id and the root aria-labelledby. Give each other input an aria-label, so that a screen reader announces the slot that has the focus. To announce a description with the field, give the root aria-describedby.

vue
<script setup lang="ts">
import { OTPField } from '@vase-ui/vue/otp-field';
</script>

<template>
  <div>
    <label id="verification-code-label" for="verification-code">Verification code</label>
    <OTPField.Root
      id="verification-code"
      :length="6"
      aria-labelledby="verification-code-label"
      aria-describedby="verification-code-description"
    >
      <OTPField.Input />
      <OTPField.Input aria-label="Character 2 of 6" />
      <OTPField.Input aria-label="Character 3 of 6" />
      <OTPField.Input aria-label="Character 4 of 6" />
      <OTPField.Input aria-label="Character 5 of 6" />
      <OTPField.Input aria-label="Character 6 of 6" />
    </OTPField.Root>
    <p id="verification-code-description">Enter the 6-character code we sent to your device.</p>
  </div>
</template>

In a Field, Field.Label names the group and each input that has no aria-label of its own.

Submitting on completion ​

Set autoSubmit to submit the form of the field when each slot has a character. To act on the completion with no submit, listen to valueComplete.

Alphanumeric verification codes ​

Set validationType to alphanumeric for recovery, backup or invite codes that mix letters and numbers.

Accept letters and numbers for backup codes such as A7C9XZ.

vue
<script setup lang="ts">
import { useId } from 'vue';
import { OTPField } from '@vase-ui/vue/otp-field';
import styles from './index.module.css';

const CODE_LENGTH = 6;

const id = useId();
const labelId = `${id}-label`;
const descriptionId = `${id}-description`;
</script>

<template>
  <div :class="styles.Field">
    <label :id="labelId" :for="id" :class="styles.Label">Recovery code</label>
    <OTPField.Root
      :id="id"
      :aria-labelledby="labelId"
      :length="CODE_LENGTH"
      validation-type="alphanumeric"
      :aria-describedby="descriptionId"
      :class="styles.Root"
    >
      <OTPField.Input
        v-for="index in CODE_LENGTH"
        :key="index"
        :class="styles.Input"
        :aria-label="index === 1 ? undefined : `Character ${index} of ${CODE_LENGTH}`"
      />
    </OTPField.Root>
    <p :id="descriptionId" :class="styles.Description">
      Accept letters and numbers for backup codes such as
      <span :class="styles.Code">A7C9XZ</span>.
    </p>
  </div>
</template>
css
.Field {
  display: flex;
  flex-direction: column;
  align-items: start;
  gap: 0.25rem;
  width: 100%;
  max-width: 20rem;
}

.Label {
  font-size: 0.875rem;
  line-height: 1.25rem;
  font-weight: 700;
  color: oklch(14.5% 0 0deg);

  @media (prefers-color-scheme: dark) {
    color: white;
  }
}

.Root {
  display: flex;
  gap: 0.5rem;
  width: 100%;
}

.Input {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  border: 1px solid oklch(14.5% 0 0deg);
  width: 2.5rem;
  height: 2.5rem;
  border-radius: 0;
  font-family: inherit;
  font-size: 1rem;
  line-height: 1.5rem;
  font-weight: 400;
  text-align: center;
  background-color: white;
  color: oklch(14.5% 0 0deg);

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
  }

  &:focus {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}

.Description {
  margin: 0;
  font-size: 0.875rem;
  line-height: 1.25rem;
  color: oklch(43.9% 0 0deg);

  @media (prefers-color-scheme: dark) {
    color: oklch(70.8% 0 0deg);
  }
}

.Code {
  font-family:
    'Paper Mono', ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono',
    'Courier New', monospace;
}
vue
<script setup lang="ts">
import { useId } from 'vue';
import { OTPField } from '@vase-ui/vue/otp-field';

const CODE_LENGTH = 6;

const id = useId();
const labelId = `${id}-label`;
const descriptionId = `${id}-description`;
</script>

<template>
  <div class="flex w-full max-w-80 flex-col items-start gap-1">
    <label :id="labelId" :for="id" class="text-sm font-bold text-neutral-950 dark:text-white"
      >Recovery code</label
    >
    <OTPField.Root
      :id="id"
      :aria-labelledby="labelId"
      :length="CODE_LENGTH"
      validation-type="alphanumeric"
      :aria-describedby="descriptionId"
      class="flex w-full gap-2"
    >
      <OTPField.Input
        v-for="index in CODE_LENGTH"
        :key="index"
        class="m-0 h-10 w-10 rounded-none border border-neutral-950 bg-white dark:bg-neutral-950 text-center font-inherit text-base font-normal text-neutral-950 focus:outline-2 focus:-outline-offset-1 focus:outline-neutral-950 dark:focus:outline-white dark:border-white dark:text-white"
        :aria-label="index === 1 ? undefined : `Character ${index} of ${CODE_LENGTH}`"
      />
    </OTPField.Root>
    <p :id="descriptionId" class="m-0 text-sm text-neutral-600 dark:text-neutral-400">
      Accept letters and numbers for backup codes such as
      <code class="font-mono">A7C9XZ</code>.
    </p>
  </div>
</template>

Grouped layouts ​

Put sets of inputs in your own layout elements. Add OTPField.Separator to show the code in smaller groups, such as 123-456.

vue
<script setup lang="ts">
import { useId } from 'vue';
import { OTPField } from '@vase-ui/vue/otp-field';
import styles from './index.module.css';

const OTP_LENGTH = 6;

const id = useId();
const labelId = `${id}-label`;
</script>

<template>
  <div :class="styles.Field">
    <label :id="labelId" :for="id" :class="styles.Label">Verification code</label>
    <OTPField.Root :id="id" :aria-labelledby="labelId" :length="OTP_LENGTH" :class="styles.Root">
      <div :class="styles.Group">
        <OTPField.Input
          v-for="index in 3"
          :key="index"
          :class="styles.Input"
          :aria-label="index === 1 ? undefined : `Character ${index} of ${OTP_LENGTH}`"
        />
      </div>
      <OTPField.Separator :class="styles.Separator" />
      <div :class="styles.Group">
        <OTPField.Input
          v-for="index in 3"
          :key="index + 3"
          :class="styles.Input"
          :aria-label="`Character ${index + 3} of ${OTP_LENGTH}`"
        />
      </div>
    </OTPField.Root>
  </div>
</template>
css
.Field {
  display: flex;
  flex-direction: column;
  align-items: start;
  gap: 0.25rem;
  width: 100%;
  max-width: 20rem;
}

.Label {
  font-size: 0.875rem;
  line-height: 1.25rem;
  font-weight: 700;
  color: oklch(14.5% 0 0deg);

  @media (prefers-color-scheme: dark) {
    color: white;
  }
}

.Root {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  width: 100%;
}

.Group {
  display: flex;
  gap: 0.5rem;
}

.Input {
  box-sizing: border-box;
  margin: 0;
  padding: 0;

  border: 1px solid oklch(14.5% 0 0deg);
  width: 2.5rem;
  height: 2.5rem;
  border-radius: 0;
  font-family: inherit;
  font-size: 1rem;
  line-height: 1.5rem;
  font-weight: 400;
  text-align: center;
  background-color: white;
  color: oklch(14.5% 0 0deg);

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
  }

  &:focus {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}

.Separator {
  width: 1rem;
  height: 1px;
  background-color: currentColor;
  color: oklch(14.5% 0 0deg);

  @media (prefers-color-scheme: dark) {
    color: white;
  }
}
vue
<script setup lang="ts">
import { useId } from 'vue';
import { OTPField } from '@vase-ui/vue/otp-field';

const OTP_LENGTH = 6;

const id = useId();
const labelId = `${id}-label`;
</script>

<template>
  <div class="flex w-full max-w-80 flex-col items-start gap-1">
    <label :id="labelId" :for="id" class="text-sm font-bold text-neutral-950 dark:text-white"
      >Verification code</label
    >
    <OTPField.Root
      :id="id"
      :aria-labelledby="labelId"
      :length="OTP_LENGTH"
      class="flex w-full items-center gap-2"
    >
      <div class="flex gap-2">
        <OTPField.Input
          v-for="index in 3"
          :key="index"
          class="m-0 h-10 w-10 rounded-none border border-neutral-950 bg-white dark:bg-neutral-950 text-center font-inherit text-base font-normal text-neutral-950 focus:outline-2 focus:-outline-offset-1 focus:outline-neutral-950 dark:focus:outline-white dark:border-white dark:text-white"
          :aria-label="index === 1 ? undefined : `Character ${index} of ${OTP_LENGTH}`"
        />
      </div>
      <OTPField.Separator class="h-px w-4 bg-current text-neutral-950 dark:text-white" />
      <div class="flex gap-2">
        <OTPField.Input
          v-for="index in 3"
          :key="index + 3"
          class="m-0 h-10 w-10 rounded-none border border-neutral-950 bg-white dark:bg-neutral-950 text-center font-inherit text-base font-normal text-neutral-950 focus:outline-2 focus:-outline-offset-1 focus:outline-neutral-950 dark:focus:outline-white dark:border-white dark:text-white"
          :aria-label="`Character ${index + 3} of ${OTP_LENGTH}`"
        />
      </div>
    </OTPField.Root>
  </div>
</template>

Custom normalization ​

Use normalizeValue to change the accepted characters before the code changes, for example to make a code uppercase. It runs after the filter of validationType, and that filter then runs on its result again. Set validationType to none when normalizeValue is the full rule.

Use inputmode to give the keyboard a hint for a custom rule. Listen to valueInvalid to know when the field refuses characters.

Letters and digits only. Letters are converted to uppercase.

vue
<script setup lang="ts">
import { computed, useId } from 'vue';
import { OTPField } from '@vase-ui/vue/otp-field';
import { useInvalidFeedback } from '../useInvalidFeedback';
import styles from './index.module.css';

const CODE_LENGTH = 6;

function normalizeRecoveryCode(value: string) {
  return value.toUpperCase();
}

function getInvalidClassName(invalidPulse: number, evenClassName: string, oddClassName: string) {
  if (invalidPulse === 0) {
    return '';
  }

  return invalidPulse % 2 === 0 ? evenClassName : oddClassName;
}

const id = useId();
const labelId = `${id}-label`;
const descriptionId = `${id}-description`;

const {
  activeInvalidIndex,
  handleValueChange,
  handleValueInvalid,
  invalidPulse,
  setFocusedIndex,
  statusMessage,
} = useInvalidFeedback();

const invalidClassName = computed(() =>
  getInvalidClassName(invalidPulse.value, styles.InputInvalidB, styles.InputInvalidA),
);
</script>

<template>
  <div :class="styles.Field">
    <label :id="labelId" :for="id" :class="styles.Label">Recovery code</label>
    <OTPField.Root
      :id="id"
      :aria-labelledby="labelId"
      :length="CODE_LENGTH"
      validation-type="alphanumeric"
      :normalize-value="normalizeRecoveryCode"
      :aria-describedby="descriptionId"
      :class="styles.Root"
      @value-change="handleValueChange"
      @value-invalid="handleValueInvalid"
    >
      <OTPField.Input
        v-for="index in CODE_LENGTH"
        :key="index"
        :class="
          `${styles.Input} ${activeInvalidIndex === index - 1 ? invalidClassName : ''}`.trim()
        "
        :aria-label="index === 1 ? undefined : `Character ${index} of ${CODE_LENGTH}`"
        @focusin="setFocusedIndex(index - 1)"
      />
    </OTPField.Root>
    <p :id="descriptionId" :class="styles.Description">
      Letters and digits only. Letters are converted to uppercase.
    </p>
    <span aria-live="polite" :class="styles.ScreenReaderOnly">{{ statusMessage }}</span>
  </div>
</template>
ts
import { computed, onUnmounted, shallowRef } from 'vue';

export function useInvalidFeedback() {
  const focusedIndex = shallowRef(0);
  const invalidPulse = shallowRef(0);
  const statusMessage = shallowRef('');
  let invalidTimeout: ReturnType<typeof setTimeout> | null = null;
  let skipClearOnNextValueChange = false;

  onUnmounted(() => {
    if (invalidTimeout != null) {
      clearTimeout(invalidTimeout);
    }
  });

  function clearInvalidFeedback() {
    if (invalidTimeout != null) {
      clearTimeout(invalidTimeout);
      invalidTimeout = null;
    }

    invalidPulse.value = 0;
    statusMessage.value = '';
  }

  function handleValueChange() {
    if (skipClearOnNextValueChange) {
      skipClearOnNextValueChange = false;
      return;
    }

    clearInvalidFeedback();
  }

  function handleValueInvalid(value: string) {
    skipClearOnNextValueChange = true;
    invalidPulse.value += 1;
    statusMessage.value = `Unsupported characters were ignored from ${value}.`;

    if (invalidTimeout != null) {
      clearTimeout(invalidTimeout);
    }

    invalidTimeout = setTimeout(() => {
      invalidTimeout = null;
      invalidPulse.value = 0;
    }, 400);
  }

  function setFocusedIndex(index: number) {
    focusedIndex.value = index;
  }

  return {
    activeInvalidIndex: computed(() => (invalidPulse.value > 0 ? focusedIndex.value : -1)),
    invalidPulse,
    statusMessage,
    setFocusedIndex,
    handleValueChange,
    handleValueInvalid,
  };
}
css
.Field {
  display: flex;
  flex-direction: column;
  align-items: start;
  gap: 0.25rem;
  width: 100%;
  max-width: 20rem;
}

.Label {
  font-size: 0.875rem;
  line-height: 1.25rem;
  font-weight: 700;
  color: oklch(14.5% 0 0deg);

  @media (prefers-color-scheme: dark) {
    color: white;
  }
}

.Root {
  display: flex;
  gap: 0.5rem;
  width: 100%;
}

.Input {
  box-sizing: border-box;
  margin: 0;
  padding: 0;

  border: 1px solid oklch(14.5% 0 0deg);
  width: 2.5rem;
  height: 2.5rem;
  border-radius: 0;
  font-family: inherit;
  font-size: 1rem;
  line-height: 1.5rem;
  font-weight: 400;
  text-align: center;
  background-color: white;
  color: oklch(14.5% 0 0deg);

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
  }

  &:focus {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}

.InputInvalidA {
  border-color: oklch(50.5% 0.213 27.518deg);
  outline: 2px solid oklch(50.5% 0.213 27.518deg);
  outline-offset: -1px;
  animation: otp-field-shake-a 180ms ease-in-out;

  @media (prefers-color-scheme: dark) {
    border-color: oklch(70.4% 0.191 22.216deg);
    outline: 2px solid oklch(70.4% 0.191 22.216deg);
  }

  &:focus {
    outline: 2px solid oklch(50.5% 0.213 27.518deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: oklch(70.4% 0.191 22.216deg);
    }
  }
}

.InputInvalidB {
  border-color: oklch(50.5% 0.213 27.518deg);
  outline: 2px solid oklch(50.5% 0.213 27.518deg);
  outline-offset: -1px;
  animation: otp-field-shake-b 180ms ease-in-out;

  @media (prefers-color-scheme: dark) {
    border-color: oklch(70.4% 0.191 22.216deg);
    outline: 2px solid oklch(70.4% 0.191 22.216deg);
  }

  &:focus {
    outline: 2px solid oklch(50.5% 0.213 27.518deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: oklch(70.4% 0.191 22.216deg);
    }
  }
}

.Description {
  margin: 0;
  font-size: 0.875rem;
  line-height: 1.25rem;
  color: oklch(43.9% 0 0deg);

  @media (prefers-color-scheme: dark) {
    color: oklch(70.8% 0 0deg);
  }
}

.ScreenReaderOnly {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  white-space: nowrap;
  border: 0;
}

@keyframes otp-field-shake-a {
  0%,
  100% {
    transform: translateX(0);
  }

  25% {
    transform: translateX(-4px);
  }

  75% {
    transform: translateX(4px);
  }
}

@keyframes otp-field-shake-b {
  0%,
  100% {
    transform: translateX(0);
  }

  25% {
    transform: translateX(-4px);
  }

  75% {
    transform: translateX(4px);
  }
}

Masked entry ​

Give each OTPField.Input the attribute type="password" to hide the code while the user types it.

Use type="password" to obscure the code on shared screens.

vue
<script setup lang="ts">
import { useId } from 'vue';
import { OTPField } from '@vase-ui/vue/otp-field';
import styles from './index.module.css';

const CODE_LENGTH = 6;

const id = useId();
const labelId = `${id}-label`;
const descriptionId = `${id}-description`;
</script>

<template>
  <div :class="styles.Field">
    <label :id="labelId" :for="id" :class="styles.Label">Access code</label>
    <OTPField.Root
      :id="id"
      :aria-labelledby="labelId"
      :length="CODE_LENGTH"
      :aria-describedby="descriptionId"
      :class="styles.Root"
    >
      <OTPField.Input
        v-for="index in CODE_LENGTH"
        :key="index"
        type="password"
        :class="styles.Input"
        :aria-label="index === 1 ? undefined : `Character ${index} of ${CODE_LENGTH}`"
      />
    </OTPField.Root>
    <p :id="descriptionId" :class="styles.Description">
      Use <span :class="styles.Code">type="password"</span> to obscure the code on shared screens.
    </p>
  </div>
</template>
css
.Field {
  display: flex;
  flex-direction: column;
  align-items: start;
  gap: 0.25rem;
  width: 100%;
  max-width: 20rem;
}

.Label {
  font-size: 0.875rem;
  line-height: 1.25rem;
  font-weight: 700;
  color: oklch(14.5% 0 0deg);

  @media (prefers-color-scheme: dark) {
    color: white;
  }
}

.Root {
  display: flex;
  gap: 0.5rem;
  width: 100%;
}

.Input {
  box-sizing: border-box;
  margin: 0;
  padding: 0;

  border: 1px solid oklch(14.5% 0 0deg);
  width: 2.5rem;
  height: 2.5rem;
  border-radius: 0;
  font-family: inherit;
  font-size: 1rem;
  line-height: 1.5rem;
  font-weight: 400;
  text-align: center;
  background-color: white;
  color: oklch(14.5% 0 0deg);

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
  }

  &:focus {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}

.Description {
  margin: 0;
  font-size: 0.875rem;
  line-height: 1.25rem;
  color: oklch(43.9% 0 0deg);

  @media (prefers-color-scheme: dark) {
    color: oklch(70.8% 0 0deg);
  }
}

.Code {
  font-family:
    'Paper Mono', ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono',
    'Courier New', monospace;
}
vue
<script setup lang="ts">
import { useId } from 'vue';
import { OTPField } from '@vase-ui/vue/otp-field';

const CODE_LENGTH = 6;

const id = useId();
const labelId = `${id}-label`;
const descriptionId = `${id}-description`;
</script>

<template>
  <div class="flex w-full max-w-80 flex-col items-start gap-1">
    <label :id="labelId" :for="id" class="text-sm font-bold text-neutral-950 dark:text-white"
      >Access code</label
    >
    <OTPField.Root
      :id="id"
      :aria-labelledby="labelId"
      :length="CODE_LENGTH"
      :aria-describedby="descriptionId"
      class="flex w-full gap-2"
    >
      <OTPField.Input
        v-for="index in CODE_LENGTH"
        :key="index"
        type="password"
        class="m-0 h-10 w-10 rounded-none border border-neutral-950 bg-white dark:bg-neutral-950 text-center font-inherit text-base font-normal text-neutral-950 focus:outline-2 focus:-outline-offset-1 focus:outline-neutral-950 dark:focus:outline-white dark:border-white dark:text-white"
        :aria-label="index === 1 ? undefined : `Character ${index} of ${CODE_LENGTH}`"
      />
    </OTPField.Root>
    <p :id="descriptionId" class="m-0 text-sm text-neutral-600 dark:text-neutral-400">
      Use <code class="font-mono">type="password"</code> to obscure the code on shared screens.
    </p>
  </div>
</template>

API reference ​

OTPField.Root ​

Groups all OTP field parts and manages their state. Renders a <div> element with the role group. Its last child is a hidden <input> that gives the code to a form. Do not select the last slot with :last-child or :last-of-type.

Props

PropTypeDefaultDescription
autocompletestring | undefined'one-time-code'The autocomplete of the first slot and of the form input.
autoSubmitboolean | undefinedfalseThe field submits its form when the code becomes complete.
defaultValuestring | undefinedThe code of a field that owns its code, at the mount and at a native reset of the form.
disabledboolean | undefinedfalseThe user cannot change the code, and the form data has no code.
formstring | undefinedThe id of the form that owns the inputs of the field, for a field outside that form.
idstring | undefinedThe id of the first slot. The other slots get {id}-2, {id}-3 and the next numbers.
inputmode"none" | "text" | "tel" | "url" | "email" | "numeric" | "decimal" | "search" | undefinedThe keyboard hint of the slots and of the form input. With none, the hint follows validationType.
lengthnumberRequiredThe number of slots. The root cuts the code to it and finds the completion from it. With it, the form input has the validation of a whole code before the slots hydrate.
modelValuestring | undefinedThe code. With no value, the field owns its code.
namestring | undefinedThe name of the code in the form data. The form input gives the whole code, and the slots have no name. The name of a Field.Root wins.
normalizeValue((value: string) => string) | undefinedChanges the code after the field removes whitespace and each character that validationType refuses. It runs for the first code, for each model value and for each edit. The filter of validationType then runs on its result again, and the field cuts the result to length. The field can run it more than one time on the same code, so its result must not change when it runs on its own result. valueInvalid tells when it refuses a character of typed or pasted text.
readonlyboolean | undefinedfalseThe user cannot change the code. The field stays in the tab order.
requiredboolean | undefinedfalseThe user must give a code before a submit.
validationTypeOTPFieldRootValidationType | undefined'numeric'The characters that a slot accepts.
askeyof HTMLElementTagNameMap | Component | GenericComponent | undefinedA tag or a component that the part renders in place of its own element, with the same attributes and content. The element slot wins over it.

Slots

SlotSlot propsDescription
default
state: OTPFieldRootState
The content of the part.
element
props: Record<string, unknown>
elementRef: (target: unknown) => void
state: OTPFieldRootState
Renders your element in place of the element of the root. Bind props with v-bind and elementRef with :ref. The root renders the form input after your element.

Events

EventArgumentsDescription
valueChange[value: string, eventDetails: OTPFieldRootChangeEventDetails]The user changes the code. details.reason is 'input-change' for typed text or a fill, 'input-clear' for a removed character, 'input-paste' for a paste, and 'keyboard' for a key. details.cancel() keeps the code as it was.
update:modelValue[value: string]Comes after the change event with the new value, unless a listener cancels the change. v-model uses it.
valueInvalid[value: string, eventDetails: OTPFieldRootInvalidEventDetails]Typed, pasted or filled text has a character that validationType or normalizeValue refuses. It comes before the code changes. value is the text of the user.
valueComplete[value: string, eventDetails: OTPFieldRootCompleteEventDetails]The code becomes complete, or the user pastes a complete code in a complete field. It comes after valueChange and the change of the code. A pasted code that equals the code gives no valueChange. With autoSubmit, the form submits just after it.

Exposed

MemberTypeDescription
elementHTMLElement | nullThe element of the part, or null while it is not mounted.

Selectors

SelectorDescription
[data-complete]Each slot has a character.
[data-filled]A slot has a character.
[data-disabled]The field is disabled.
[data-readonly]The field is read-only.
[data-required]The field is required.
[data-valid]The code is valid, in a Field.Root.
[data-invalid]The code is invalid, in a Field.Root.
[data-touched]The focus left the field one time or more, in a Field.Root.
[data-dirty]The code differs from the first code, in a Field.Root.

OTPField.Input ​

An individual OTP character input. Renders an <input> element.

Slots

SlotSlot propsDescription
element
props: Record<string, unknown>
elementRef: (target: unknown) => void
state: OTPFieldInputState
Renders your element in place of the element of the part. Bind props with v-bind and elementRef with :ref.

Exposed

MemberTypeDescription
elementHTMLInputElement | nullThe element of the part, or null while it is not mounted.

Selectors

SelectorDescription
[data-complete]Each slot has a character.
[data-filled]The slot has a character.
:disabledThe field is disabled.
:read-onlyThe field is read-only or disabled.
:requiredThe field is required.
[aria-invalid="true"]The code is invalid, in a Field.Root.
[data-valid]The code is valid, in a Field.Root.
[data-touched]The focus left the field one time or more, in a Field.Root.
[data-dirty]The code differs from the first code, in a Field.Root.

OTPField.Separator ​

A separator element accessible to screen readers. Renders a <div> element.

Props

PropTypeDefaultDescription
orientation"horizontal" | "vertical" | undefined'horizontal'The orientation of the separator.
askeyof HTMLElementTagNameMap | Component | GenericComponent | undefinedA tag or a component that the part renders in place of its own element, with the same attributes and content. The element slot wins over it.

Slots

SlotSlot propsDescription
default
state: SeparatorState
Content, such as a glyph between two groups. Assistive technology does not read it.
element
props: Record<string, unknown>
elementRef: (target: unknown) => void
state: SeparatorState
Renders your element in place of the element of the part. Bind props with v-bind and elementRef with :ref.

Exposed

MemberTypeDescription
elementHTMLDivElement | nullThe element of the part, or null while it is not mounted.

Selectors

SelectorDescription
[aria-orientation="vertical"]The separator is vertical.

Differences from Base UI ​

Vase UI ports OTP Field from Base UI 1.9.0.

API ​

Base UIVase UI
OTPField.Rootv-model replaces value and onValueChange. autocomplete, inputmode and readonly replace autoComplete, inputMode and readOnly, also in the state. type="password" on each OTPField.Input is the native attribute on the element that it changes, so the root has no mask. CSS selects :focus-within, so the state has no focused, and the group has no data-focused. The part stops no event, and details.event.target is the element, so the details of a change have no allowPropagation, isPropagationAllowed or trigger.
OTPField.InputThe attributes of an input type the part, so it has no props type. CSS selects :disabled, :read-only, :required, [aria-invalid="true"] and :focus on the same input, so it has no data-disabled, data-readonly, data-required, data-invalid and data-focused. readonly replaces readOnly in the state, and the state has no focused.

Behavior ​

Vase UIEvidence
With validationType="none", each Unicode code point takes one slot. Typed text, a paste, a deletion, the focus and the completion count the slots in the same way. Base UI normalizes the code by code point, but it counts the slots and the completion by UTF-16 code unit.
OTP Field counts the rendered slots after the list updates, so a change of length and of the slots together gives no warning. Base UI can warn with the earlier count of slots.
A control in a field keeps the id of the developer in the server HTML when no Field.Label of the field renders before it, and a label that renders after the control has that id in for. When a label renders before the control, the control has the generated id of the field until the hydration, because that label names the generated id. Then the control takes its id, and the label follows. In each order, the label names the control in the server HTML. Base UI gives each control in a field the generated id until the hydration, also where no label needs it.

The handbook gives the differences that all components share: Styling, Animation, Composition, Customization, Forms and TypeScript.