Forms
OTP input
Enters a one-time code, like the one sent to a phone to confirm a sign-in.
Installation
npx sinaui add otp-inputCopy src/lib/ui/OtpInput.svelte and tokens.css. No dependencies.
Examples
Verification code
Paste the whole code, or let the phone fill it in from the message. A wrong code shakes the boxes and clears them.
We sent a 6-digit code to your phone. (Try 314159.)
<script lang="ts">
import OtpInput from '#lib/ui/OtpInput.svelte';
let code = $state('');
let error = $state<string>();
let verified = $state(false);
// The error goes as soon as they start typing again.
$effect(() => {
if (code) error = undefined;
});
// Stands in for your server; 314159 is the right code here.
function check(entered: string) {
verified = entered === '314159';
error = verified ? undefined : "That code isn't right. Check the message and try again.";
if (!verified) code = '';
}
</script>
<OtpInput
label="Verification code"
bind:value={code}
groups={[3, 3]}
name="code"
hint="We sent a 6-digit code to your phone. (Try 314159.)"
{error}
oncomplete={check}
/>
{#if verified}<p class="ok" role="status">Verified. Welcome back to the reading room.</p>{/if}
<style>
.ok {
margin: 0.75rem 0 0;
color: color-mix(in srgb, var(--ui-accent) 80%, var(--ui-fg));
font-weight: 500;
}
</style>Letters and digits
Typed in any case, shown in capitals.
Letters and digits, on your loan slip.
<script lang="ts">
import OtpInput from '#lib/ui/OtpInput.svelte';
let pickup = $state('');
</script>
<OtpInput
label="Pickup code"
bind:value={pickup}
length={4}
mode="text"
hint="Letters and digits, on your loan slip."
/>Props
| Prop | Type | Default |
|---|---|---|
label | string (required) | |
value | string, bindable | '' |
length | number | 6 |
groups | number[], e.g. [3, 3] | |
mode | 'numeric' | 'text' | 'numeric' |
oncomplete | (code) => void | |
name, hint, error | string | |
disabled | boolean | false |
Accessibility
- One real text field under the boxes: screen readers hear a single field with its label, not six.
- It asks for
one-time-codeautofill, so phones offer the code from the message. - Numeric codes show the number keypad on phones.