Input OTP
一次性验证码输入,一格一个字符:每格是 Input 样式的小号斜切输入槽,字符以瘦高的斜体显示。
安装
# once per project: where @zzzui items come frompnpm dlx shadcn@latest registry add @zzzui=https://zzzui.catforest.dev/r/{name}.jsonpnpm dlx shadcn@latest add @zzzui/input-otp示例
四位,以及分两组的六位
Four characters, on the back of the crate.
import { Field, FieldDescription, FieldLabel } from "@/components/zero/field";import { InputOTP, InputOTPSeparator, InputOTPSlot,} from "@/components/zero/input-otp";export default function InputOTPCode() { return ( <div className="grid gap-8"> <Field> <FieldLabel>Gate code</FieldLabel> <InputOTP length={4} validationType="alphanumeric" /> <FieldDescription> Four characters, on the back of the crate. </FieldDescription> </Field> <Field> <FieldLabel>Sign-off code</FieldLabel> <InputOTP length={6}> <InputOTPSlot /> <InputOTPSlot aria-label="Character 2 of 6" /> <InputOTPSlot aria-label="Character 3 of 6" /> <InputOTPSeparator /> <InputOTPSlot aria-label="Character 4 of 6" /> <InputOTPSlot aria-label="Character 5 of 6" /> <InputOTPSlot aria-label="Character 6 of 6" /> </InputOTP> </Field> </div> );}行为
输入一个字符后,焦点移至下一格;按 Backspace 退回上一格;粘贴则一次填满整行。正在输入的格子显示焦点框;位于校验未通过的 Field 中时,各格改为危险色描边。默认仅接受数字,通过 validationType 也可接受字母。
不传子元素时,InputOTP 绘制 length 个格子;配合 InputOTPSlot 与 InputOTPSeparator 可将格子分组。通过 Field 中的 FieldLabel(或指向其 id 的 label)为它命名:第一格使用该名称,其余各格的可访问名称标明各自是第几个字符。
属性
InputOTP
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| length | number | — | 字符数。 |
| validationType | "numeric" | "alpha" | "alphanumeric" | "none" | "numeric" | 每格接受的字符类型。 |
| onValueComplete | (value) => void | — | 所有格子填满时调用。 |
| label | (character: number, length: number) => string | "Character {n} of {length}" | 每个自动绘制的格子的可访问名称,由序号(从 1 起)与总长度生成。 |
另可传入 Base UI OTPField.Root 的全部属性。
InputOTPSlot, InputOTPSeparator
另可传入 Base UI OTPField.Input 的全部属性。