# Phone input

> An international hairline phone input with searchable calling codes, caret-safe national formatting, automatic +E.164 country detection and structured output.

International phone inputs usually bring heavy dependencies, inconsistent emoji flags across operating systems and aggressive formatters that jump the cursor while editing. PhoneInput ships a built-in table of 36 major markets with crisp monospace ISO badges that render identically on every platform, caret-safe as-you-type national grouping and a searchable country popover with full keyboard navigation. Paste any full international number (+44 7700 900077, +91 98765 43210, +81 90-1234-5678) and it detects the country automatically, switches the dial code, strips trunk zeros where required and sweeps an optical 8×8 Bayer confirmation pulse across the lower rail. On completion it emits clean structured E.164 data and exports parsePhoneNumber() so server actions and forms share the exact same rules.

## Install

```bash
npx shadcn@latest add https://hairlineui.com/r/phone-input.json
```

Needs React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

- npm: `lucide-react`
- Hairline UI components it needs (the CLI installs them too): `text-morph`
- Docs and live preview: https://hairlineui.com/ui/phone-input
- Registry item (source): https://hairlineui.com/r/phone-input.json

## Usage

```tsx
import { PhoneInput } from "@/components/phone-input";

<PhoneInput
  label="Mobile number"
  defaultCountry="US"
  onChange={(phone) => {
    if (phone.valid) setE164(phone.e164);
  }}
/>
```

## SMS verification step wired to clean E.164 submission

Read phone.valid and phone.e164 straight from onChange so your SMS endpoint only receives verified international strings.

```tsx
"use client";
import { useState } from "react";
import { PhoneInput, type PhoneValue } from "@/components/phone-input";

export function SmsSignIn({ onSendCode }: { onSendCode: (e164: string) => Promise<void> }) {
  const [phone, setPhone] = useState<PhoneValue | null>(null);

  return (
    <form
      onSubmit={(e) => {
        e.preventDefault();
        if (phone?.valid) void onSendCode(phone.e164);
      }}
      className="space-y-3"
    >
      <PhoneInput label="Mobile number" defaultCountry="US" onChange={setPhone} />
      <button
        type="submit"
        disabled={!phone?.valid}
        className="h-10 w-full rounded-xl bg-foreground text-sm font-medium text-background disabled:opacity-40"
      >
        Send verification code
      </button>
    </form>
  );
}
```

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value / defaultValue / onChange` | `string / string / (v: PhoneValue) => void` | – | Controlled or uncontrolled E.164 or national value plus callback emitting { e164, national, digits, country, dialCode, valid }. |
| `country / defaultCountry / onCountryChange` | `string / string / (iso) => void` | `"US"` | Controlled or initial ISO 3166-1 alpha-2 country code. |
| `countries` | `PhoneCountry[]` | `PHONE_COUNTRIES (36)` | Optional subset or custom calling-code list. |
| `validateOnBlur / clearable / label / disabled / sound` | `boolean / boolean / string / boolean / boolean` | `true / true / "Phone number" / false / false` | Incomplete-number blur validation, inline clear button, accessible label, disabled state and opt-in Web Audio cues. |
| `parsePhoneNumber / PHONE_COUNTRIES` | `exported utility / array` | – | Parse any E.164 or national string outside the input with identical country and length rules. |

## States

- **empty**: Shows active country ISO badge, calling code and a realistic national placeholder example for that market.
- **typing**: Formats national digits live into the country pattern while restoring the caret cleanly after the exact digit edited.
- **country detected**: Pasting an international number switches the calling code automatically and sweeps a brief blue Bayer pulse across the lower edge.
- **valid**: When digit length matches the country rules, an emerald check morphs into place alongside a quiet emerald Bayer floor confirmation.
- **incomplete on blur**: A damped horizontal recoil nudges the field with a brief rose Bayer floor pulse and unfolds an exact digit-count message inline.
- **country popover open**: Searchable hairline listbox filters by country name, ISO code or dial prefix with keyboard navigation.

## What it handles

Good phone inputs should format cleanly without stealing the cursor, recognise pasted international codes automatically and hand clean E.164 strings to your backend.

- **Caret-safe national grouping**: Tracks exact digit counts ahead of the cursor before formatting so inserting or deleting digits in the middle never jumps the caret.
- **Automatic +E.164 country detection**: Pasting or typing a number starting with + or 00 matches the longest calling code, switches the country selector and strips optional trunk zeros.
- **Zero emoji-flag glitches**: Uses crisp hairline monospace ISO badges (US, GB, IN) beside tabular dial codes so rendering stays sharp on Windows, Linux and macOS alike.
- **Searchable keyboard country picker**: Filter all 36 built-in countries by name, ISO code or calling code with Arrow keys, Enter and Escape.
- **Optical valid completion and blur guard**: Valid national lengths morph in an emerald check with a quiet 8×8 Bayer floor sweep; incomplete blurs trigger a gentle spring recoil and inline length hint.
- **Structured output and parser helper**: Emits { e164, national, digits, country, dialCode, valid } on every change and exports parsePhoneNumber() and PHONE_COUNTRIES.

## Replaces

react-phone-number-input, libphonenumber-js UI wrapper, custom dial-code select, flag sprite sheets

## Where it fits

- **Account sign-up and SMS 2FA**: Collect clean E.164 strings (+14155550192) ready for Twilio, Clerk or Supabase Auth without pulling in libphonenumber.
- **Checkout and shipping forms**: Format national numbers cleanly as customers type without jumping the caret on mid-string edits.
- **CRM and contact drawers**: Paste international numbers from emails or Slack and let the picker switch countries automatically.
- **Regional SaaS onboarding**: Pass a filtered countries prop when your product operates in a specific set of markets.

## Notes

- Calling-code detection sorts longest prefixes first (+971 before +9, +353 before +35) and respects the active country on shared codes such as +1 (US and Canada).
- Monospace ISO badges replace emoji flags so rendering stays crisp and uniform on Windows, Linux and macOS.
- The 8×8 Bayer optical floor sleeps completely at 0% CPU except during the ~0.5s valid, auto-detect or error confirmation sweep.
- Under prefers-reduced-motion: reduce, horizontal recoil and Bayer sweeps are skipped while all formatting, auto-detection and keyboard navigation remain active.

License: MIT (https://hairlineui.com/license#components)
