111k

Input OTP

一个支持复制粘贴的一次性密码输入组件,且具有可访问性。

1
2
3
4
5
6
import {
  InputOTP,
  InputOTPGroup,

关于

Input OTP 基于 input-otp 构建,作者是 @guilherme_rodz

安装

pnpm dlx shadcn@latest add input-otp

用法

import {
  InputOTP,
  InputOTPGroup,
  InputOTPSeparator,
  InputOTPSlot,
} from "@/components/ui/input-otp"
<InputOTP maxLength={6}>
  <InputOTPGroup>
    <InputOTPSlot index={0} />
    <InputOTPSlot index={1} />
    <InputOTPSlot index={2} />
  </InputOTPGroup>
  <InputOTPSeparator />
  <InputOTPGroup>
    <InputOTPSlot index={3} />
    <InputOTPSlot index={4} />
    <InputOTPSlot index={5} />
  </InputOTPGroup>
</InputOTP>

模式

使用 pattern 属性可以为 OTP 输入框定义自定义模式。

import { REGEXP_ONLY_DIGITS_AND_CHARS } from "input-otp"
 
;<InputOTP maxLength={6} pattern={REGEXP_ONLY_DIGITS_AND_CHARS}>
  ...
</InputOTP>
"use client"

import { Field, FieldLabel } from "@/components/ui/field"

示例

分隔符

使用 <InputOTPSeparator /> 组件可在输入组之间添加分隔符。

import {
  InputOTP,
  InputOTPGroup,

禁用

使用 disabled 属性可以禁用输入框。

1
2
3
4
5
6
import {
  InputOTP,
  InputOTPGroup,

受控

使用 valueonChange 属性来控制输入值。

Enter your one-time password.
"use client"

import * as React from "react"

无效

在槽位上使用 aria-invalid 可以显示错误状态。

0
0
0
0
0
0
"use client"

import * as React from "react"

四位数字

这是 PIN 码的常见模式。它使用 pattern={REGEXP_ONLY_DIGITS} 属性。

"use client"

import {

字母数字

使用 REGEXP_ONLY_DIGITS_AND_CHARS 可同时接受字母和数字。

"use client"

import {

表单

Verify your login
Enter the verification code we sent to your email address: m@example.com.

I no longer have access to this email address.

Having trouble signing in? Contact support
import { Button } from "@/components/ui/button"
import {
  Card,

RTL

要在 shadcn/ui 中启用 RTL 支持,请参见 RTL 配置指南

1
2
3
4
5
6
"use client"

import * as React from "react"

API 参考

更多信息请参见 input-otp 文档。