Skip to content
shadcn.io

shadcn.io is not affiliated with official shadcn/ui

Input OTP examples · Standard

OTP in Form with Validation Input OTP for React

A one-time code form that checks the code has six characters when it's submitted.

Framework
UI library

A code field in a real form needs a label, a description and an error. This example wraps InputOTP in a Field with One-Time Password, a description saying where the code was sent, and a FieldError that shows Your one-time password must be 6 characters. when the form is submitted too early.

Preview

Preview width

Installation

Sign in to get your install command
Free with an account. It carries your token, so the CLI installs everything in one go.

FAQ

How is the code validated?

On submit: the handler stops the page from reloading, joins the code, and sets an error when it's shorter than six characters. Otherwise it accepts the code.

How is the error shown?

invalid on Field follows the error and FieldError shows the message. Editing the code clears it.

Can I use a form library instead?

Yes. Set invalid from the library's field state and put its message in FieldError; the field doesn't depend on how you validate.

What happens after a valid submit?

The example shows the result in a status line under the form instead of calling an API. Replace that with your request, and show its error in FieldError when the code is rejected. Here it reads You submitted the following values: and the code.

How is One-Time Password tied to the field?

FieldLabel sets htmlFor to otp-form-pin, the id on InputOTP, which it passes to its input.

How is the value kept?

In state, written on every change. The value is one string, and onChange receives the next string.