Skip to main content

OTPInput

OTPInput

One-time password input for verification codes

Tags: component form authentication

View Demo

OTPInput provides a specialized input for entering one-time passwords and verification codes.

Import​

<script>
  import { OTPInput } from '@classic-homes/theme-svelte';
</script>

Basic Usage​

<script>
  let code = $state('');
</script>

<OTPInput bind:value={code} />

Props​

Prop Type Default Description
value string '' Current value (bindable)
length number 6 Number of digits
disabled boolean false Disables the input
required boolean false Marks field as required
type 'numeric' | 'alphanumeric' 'numeric' Input type
name string - Name attribute for form submission
id string - Element ID (auto-generated if empty)
label string - Label text
hint string - Hint text below the input
error string - Error message
onComplete (value: string) => void - Callback when all digits entered
onValueChange (value: string) => void - Callback when value changes
class string - Additional CSS classes

With Label and Hint​

<OTPInput
  label="Verification Code"
  hint="Enter the 6-digit code sent to your email"
  bind:value={code}
/>

Custom Length​

Change the number of digits:

<OTPInput label="PIN" hint="Enter your 4-digit PIN" bind:value={code} length={4} />

Alphanumeric Input​

Accept letters and numbers:

<OTPInput label="Backup Code" bind:value={code} type="alphanumeric" length={8} />

Auto Submit​

Trigger action when complete:

<OTPInput
  label="Verification Code"
  bind:value={code}
  onComplete={(code) => {
    verifyCode(code);
  }}
/>

Validation​

<OTPInput
  label="Code"
  bind:value={code}
  error={verificationFailed ? 'Invalid code. Please try again.' : ''}
/>

Accessibility​

The OTPInput component includes:

  • Auto-advance on digit entry
  • Backspace navigation between inputs
  • Paste support for full code
  • Screen reader announcements
  • Auto-generated IDs link labels to inputs
  • aria-describedby connects hint and error messages
  • aria-invalid set when error is present
  • autocomplete="one-time-code" for browser autofill

Examples​

Verification Flow​

<script>
  let code = $state('');
  let error = $state('');
  let verifying = $state(false);

  async function handleComplete(value: string) {
    verifying = true;
    error = '';

    try {
      await verifyOTP(value);
      // Success - redirect
    } catch {
      error = 'Invalid verification code';
      code = '';
    } finally {
      verifying = false;
    }
  }
</script>

<div class="text-center space-y-4">
  <OTPInput
    label="Verification Code"
    hint="Enter the 6-digit code sent to your email"
    bind:value={code}
    {error}
    onComplete={handleComplete}
  />
  {#if verifying}
    <Spinner label="Verifying..." />
  {/if}
</div>

Two-Factor Authentication​

<OTPInput
  label="Authentication Code"
  hint="Enter code from your authenticator app"
  bind:value={twoFactorCode}
  length={6}
  onComplete={verify2FA}
/>
On this page