Перейти к содержимому

VerificationCode ​

Поле для кода подтверждения из четырёх или шести цифр в крупном и компактном виде: ячейки и разделитель добавляют части, а подпись и подсказку даёт Field.

Исходник

Импорт ​

ts
import { VerificationCode, VerificationCodeSlot, VerificationCodeSeparator } from '@prosper/ui'

Анатомия ​

vue
<VerificationCode>
  <VerificationCodeSlot />
  <VerificationCodeSeparator />
</VerificationCode>

Примеры ​

По умолчанию ​

v-model с настоящим ref, а событие complete приходит, когда набраны все цифры.

vue
<script setup lang="ts">
import { ref } from 'vue'
import {
  Field,
  FieldHint,
  FieldLabel,
  VerificationCode,
  VerificationCodeSlot,
} from '@prosper/ui'

const code = ref('')
const entered = ref('')
</script>

<template>
  <div
    style="
      display: flex;
      flex-direction: column;
      gap: var(--prosper-spacing-3xl);
    "
  >
    <Field>
      <FieldLabel>Код из SMS</FieldLabel>
      <VerificationCode v-model="code" :digits="4" @complete="entered = $event">
        <VerificationCodeSlot
          v-for="index in 4"
          :key="index"
          :index="index - 1"
        />
      </VerificationCode>
      <FieldHint>Мы отправили четыре цифры на ваш номер.</FieldHint>
    </Field>
    <p v-if="entered" style="margin: 0">Введён полный код: {{ entered }}</p>
  </div>
</template>

Типы ​

Компактный код со всеми размерами, а шесть цифр с дефисом помещаются в окно 320.

vue
<script setup lang="ts">
import {
  Field,
  FieldLabel,
  VerificationCode,
  VerificationCodeSeparator,
  VerificationCodeSlot,
} from '@prosper/ui'

const sizes = ['sm', 'md', 'lg', 'xl'] as const
</script>

<template>
  <div
    style="
      display: flex;
      flex-direction: column;
      gap: var(--prosper-spacing-4xl);
      min-inline-size: 0;
    "
  >
    <Field v-for="size in sizes" :key="size" :size="size">
      <FieldLabel>{{ size }}</FieldLabel>
      <VerificationCode variant="compact" :digits="4" value="123">
        <VerificationCodeSlot
          v-for="index in 4"
          :key="index"
          :index="index - 1"
        />
      </VerificationCode>
    </Field>
    <Field size="xl">
      <FieldLabel>Шесть цифр</FieldLabel>
      <VerificationCode variant="compact" value="123">
        <VerificationCodeSlot
          v-for="index in 3"
          :key="index"
          :index="index - 1"
        />
        <VerificationCodeSeparator />
        <VerificationCodeSlot
          v-for="index in 3"
          :key="index"
          :index="index + 2"
        />
      </VerificationCode>
    </Field>
  </div>
</template>

Размеры ​

Три размера ячейки: sm, md и lg, а начальный код задаёт атрибут value.

vue
<script setup lang="ts">
import {
  Field,
  FieldLabel,
  VerificationCode,
  VerificationCodeSlot,
} from '@prosper/ui'

const sizes = ['sm', 'md', 'lg'] as const
</script>

<template>
  <div
    style="
      display: flex;
      flex-direction: column;
      gap: var(--prosper-spacing-4xl);
    "
  >
    <Field v-for="size in sizes" :key="size" :size="size">
      <FieldLabel>{{ size }}</FieldLabel>
      <VerificationCode :digits="4" value="123">
        <VerificationCodeSlot
          v-for="index in 4"
          :key="index"
          :index="index - 1"
        />
      </VerificationCode>
    </Field>
  </div>
</template>

Четыре и шесть цифр ​

digits выбирает, сколько цифр принимает поле: 4 или 6 (по умолчанию), а ячейки и дефис между группами рисуют VerificationCodeSlot и VerificationCodeSeparator.

vue
<script setup lang="ts">
import {
  Field,
  FieldLabel,
  VerificationCode,
  VerificationCodeSeparator,
  VerificationCodeSlot,
} from '@prosper/ui'
</script>

<template>
  <div
    style="
      display: flex;
      flex-direction: column;
      gap: var(--prosper-spacing-4xl);
      min-inline-size: 0;
    "
  >
    <Field size="sm">
      <FieldLabel>Четыре ячейки</FieldLabel>
      <VerificationCode :digits="4" value="12">
        <VerificationCodeSlot
          v-for="index in 4"
          :key="index"
          :index="index - 1"
        />
      </VerificationCode>
    </Field>
    <Field size="sm">
      <FieldLabel>Шесть ячеек</FieldLabel>
      <VerificationCode value="123">
        <VerificationCodeSlot
          v-for="index in 3"
          :key="index"
          :index="index - 1"
        />
        <VerificationCodeSeparator />
        <VerificationCodeSlot
          v-for="index in 3"
          :key="index"
          :index="index + 2"
        />
      </VerificationCode>
    </Field>
  </div>
</template>

Состояния ​

invalid у Field включает красные ячейки, текст ошибки кладите в FieldError, а disabled отключает поле.

vue
<script setup lang="ts">
import {
  Field,
  FieldError,
  FieldLabel,
  VerificationCode,
  VerificationCodeSlot,
} from '@prosper/ui'
</script>

<template>
  <div
    style="
      display: flex;
      flex-direction: column;
      gap: var(--prosper-spacing-4xl);
    "
  >
    <Field>
      <FieldLabel>Пустое</FieldLabel>
      <VerificationCode :digits="4">
        <VerificationCodeSlot
          v-for="index in 4"
          :key="index"
          :index="index - 1"
        />
      </VerificationCode>
    </Field>
    <Field>
      <FieldLabel>Весь код</FieldLabel>
      <VerificationCode :digits="4" value="1234">
        <VerificationCodeSlot
          v-for="index in 4"
          :key="index"
          :index="index - 1"
        />
      </VerificationCode>
    </Field>
    <Field invalid>
      <FieldLabel>С ошибкой</FieldLabel>
      <VerificationCode :digits="4" value="1234">
        <VerificationCodeSlot
          v-for="index in 4"
          :key="index"
          :index="index - 1"
        />
      </VerificationCode>
      <FieldError>Код не подошёл, попробуйте ещё раз.</FieldError>
    </Field>
    <Field disabled>
      <FieldLabel>Отключённое</FieldLabel>
      <VerificationCode :digits="4" value="123">
        <VerificationCodeSlot
          v-for="index in 4"
          :key="index"
          :index="index - 1"
        />
      </VerificationCode>
    </Field>
  </div>
</template>

Обязательное поле ​

placeholder задаёт символ пустых ячеек (по умолчанию 0), required у Field включает проверку формы, а name уходит на input.

vue
<script setup lang="ts">
import {
  Field,
  FieldLabel,
  VerificationCode,
  VerificationCodeSlot,
} from '@prosper/ui'
</script>

<template>
  <Field required>
    <FieldLabel>Код из SMS</FieldLabel>
    <VerificationCode name="code" placeholder="•" :digits="4">
      <VerificationCodeSlot
        v-for="index in 4"
        :key="index"
        :index="index - 1"
      />
    </VerificationCode>
  </Field>
</template>

API ​

VerificationCode ​

Props ​

ИмяТипПо умолчаниюОписание
modelValuestring—Код: строка цифр, состояние хранит приложение и обновляет его по событию update:modelValue, а без значения поле нативное и начальный код задаёт атрибут value.
digits4 | 66Сколько цифр принимает поле: 4 или 6, а ячейки и дефис между группами рисуют VerificationCodeSlot и VerificationCodeSeparator (их индексы должны идти от нуля до digits - 1).
variant'default' | 'compact'—Вид: default рисует крупные ячейки, compact рисует ячейки высотой с поле ввода и сжимает ряд в узкой колонке, а без значения default, в виде cabinet compact.
size'sm' | 'md' | 'lg' | 'xl'—Размер ячейки: у default sm 64 px, md 80 px, lg и xl 96 px, у compact как у поля ввода; без значения берёт Field, вне Field md, в виде cabinet xl.
requiredboolean—Обязательное поле: нативный required, а без значения required берёт Field (он же рисует звёздочку у подписи).
invalidboolean—Ошибка: красные рамки ячеек и aria-invalid, а без значения её берёт Field; у отключённого поля не действует.
disabledboolean—Отключает поле: ячейки выглядят отключёнными и получают курсор not-allowed, а без значения disabled берёт Field.
autocompletestring—Подсказка автозаполнения для браузера: по умолчанию one-time-code.

События ​

ИмяТипОписание
update:modelValue(value: string) => voidПользователь изменил код, передаётся новое значение (только цифры, не длиннее digits), например для v-model; если modelValue задан и приложение его не обновило, поле вернётся к прежнему значению.
complete(value: string) => voidНабраны все цифры: приходит сразу после update:modelValue с полным кодом, в том числе при вставке и автозаполнении из SMS.

Слоты ​

ИмяТипОписание
default{}Части поля: VerificationCodeSlot для каждой ячейки и VerificationCodeSeparator между группами.

VerificationCodeSlot ​

Одна ячейка кода: показывает цифру своего номера или символ пустой ячейки и берёт состояние у VerificationCode.

Props ​

ИмяТипПо умолчаниюОписание
indexnumberобязательныйНомер ячейки с нуля: берётся цифра кода с этим номером, а активной ячейкой становится та, что получит следующую цифру.

VerificationCodeSeparator ​

Разделитель групп ячеек: по умолчанию дефис, а размер берёт от корня.

Слоты ​

ИмяТипОписание
default{}Знак разделителя вместо дефиса.

Доступность ​

КлавишаДействие
Backspaceудалить последнюю цифру в редактируемом поле
Стрелки, Home, Endкурсор остаётся в конце кода
  • Это одно нативное поле, а не шесть: input с autocomplete="one-time-code", inputmode="numeric" и pattern из digits цифр по умолчанию, поэтому автозаполнение из SMS и цифровая клавиатура работают нативно, а нарисованные ячейки и разделитель скрыты от скринридера.
  • Имя, описание, звёздочку и ошибку даёт Field, а полю без него нужно имя через aria-label, aria-labelledby или title, иначе в режиме разработки выводится предупреждение.
  • pattern по умолчанию не пропускает в форму неполный код, required — пустой, а invalid ставит aria-invalid="true" и у отключённого поля не показывается.
  • В поле остаются только цифры (полноширинные приводятся к обычным), длина обрезается до digits, вставка заменяет код целиком, а в поле readonly игнорируется.
  • Щелчок по ячейке ставит курсор в конец кода.
  • Корень это div с class и style, name, form, id, readonly, autofocus и aria-* уходят на поле, а placeholder задаёт только символ пустых ячеек и на input не попадает.