Phone input
Country calling codes and a real telephone field with progressive international normalization and length feedback.
pnpm dlx shadcn@latest add @haze/phone-input---
import { Check, ChevronDown } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
interface Country { code: string; label: string; dialCode: string }
interface Props {
id: string;
name?: string;
label?: string;
country?: string;
countries?: Country[];
value?: string;
required?: boolean;
disabled?: boolean;
class?: string;
[key: string]: unknown;
}
const { id, name = id, label = "Phone number", country = "GB", countries = [{ code: "GB", label: "United Kingdom", dialCode: "44" }, { code: "US", label: "United States", dialCode: "1" }, { code: "BA", label: "Bosnia and Herzegovina", dialCode: "387" }, { code: "DE", label: "Germany", dialCode: "49" }], value = "", required, disabled, class: className, ...rest } = Astro.props;
const field = "h-10 min-w-0 w-full rounded-lg border border-frame-input bg-field px-2.5 text-sm tracking-[-0.01em] text-foreground transition-[border-color,background-color,box-shadow] duration-150 ease-snappy hover:border-frame-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/24 focus-visible:outline-hidden disabled:cursor-not-allowed disabled:bg-muted disabled:opacity-50 aria-invalid:border-destructive aria-invalid:focus-visible:ring-destructive/24";
---
<div data-haze-phone-input class={cn("group/phone grid min-w-0 gap-2", className)}>
<label for={id} class="text-[0.8125rem]/5 font-medium">{label}</label>
<div class="grid grid-cols-1 gap-2 sm:grid-cols-[6.5rem_minmax(0,1fr)]">
<select id={`${id}-country`} name={`${name}-country`} aria-label={`${label}: country calling code`} disabled={disabled} data-phone-country class={cn(field, "px-3 group-data-enhanced/phone:hidden [&>option]:bg-popover [&>option]:text-popover-foreground")}>
{countries.map(item => <option value={item.code} title={item.label} data-dial-code={item.dialCode} data-name={item.label} selected={item.code === country}>{item.code} +{item.dialCode}</option>)}
</select>
<div data-phone-picker class="hidden min-w-0 group-data-enhanced/phone:block">
<button type="button" id={`${id}-picker`} data-phone-trigger popovertarget={`${id}-list`} style={`anchor-name: --${id}-picker`} aria-haspopup="listbox" aria-expanded="false" aria-label={`${label}: country calling code`} disabled={disabled}
class={cn(field, "group/trigger flex cursor-pointer items-center justify-between gap-1 px-3")}>
<span data-phone-trigger-text class="truncate"></span>
<ChevronDown aria-hidden="true" class="size-4 shrink-0 text-muted-foreground transition-transform duration-200 ease-snappy group-aria-expanded/trigger:rotate-180" />
</button>
<div popover id={`${id}-list`} data-phone-list style={`position-anchor: --${id}-picker`}
class="m-auto max-h-[min(20rem,calc(100dvh-2rem))] w-64 max-w-[calc(100vw-1rem)] origin-top-left -translate-y-1 scale-[0.97] overflow-y-auto rounded-xl border border-border bg-popover p-1.5 text-[0.8125rem] leading-[1.4] text-popover-foreground opacity-0 shadow-float backdrop:bg-background/60 transition-[opacity,scale,translate,overlay,display] transition-discrete duration-200 ease-snappy motion-reduce:transition-none open:translate-y-0 open:scale-100 open:opacity-100 starting:open:-translate-y-1 starting:open:scale-[0.97] starting:open:opacity-0 supports-[position-area:block-end]:mx-0 supports-[position-area:block-end]:my-1.5 supports-[position-area:block-end]:me-2 supports-[position-area:block-end]:backdrop:bg-transparent supports-[position-area:block-end]:[position-area:block-end_span-inline-end] supports-[position-area:block-end]:[position-try-fallbacks:flip-block,flip-inline,flip-block_flip-inline]">
<ul role="listbox" aria-label={`${label}: country calling codes`} class="grid gap-0.5">
{countries.map(item => (
<li role="option" tabindex="-1" data-option-code={item.code} data-option-dial={item.dialCode} data-option-name={item.label} aria-selected={item.code === country ? "true" : "false"}
class="group/opt flex min-h-9 cursor-pointer items-center gap-2 rounded-lg px-2.5 outline-hidden transition-colors duration-150 ease-snappy hover:bg-accent aria-selected:bg-accent focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring">
<span class="min-w-0 flex-1 truncate">{item.label}</span>
<span class="shrink-0 text-muted-foreground tabular-nums">{item.code} +{item.dialCode}</span>
<Check aria-hidden="true" class="hidden size-4 shrink-0 group-aria-selected/opt:block" />
</li>
))}
</ul>
</div>
</div>
<input {...rest} id={id} name={name} type="tel" autocomplete="tel" inputmode="tel" value={value} required={required} disabled={disabled} data-phone-number aria-describedby={`${id}-hint ${id}-error`} class={cn(field, "px-3 placeholder:text-muted-foreground")} />
</div>
<input data-phone-normalized type="hidden" name={name} disabled />
<p id={`${id}-hint`} data-phone-hint class="text-[0.8125rem]/5 wrap-anywhere text-muted-foreground">Include an area code. International numbers may start with +.</p>
<p id={`${id}-error`} data-phone-error role="status" hidden class="text-[0.8125rem]/5 text-destructive [&[hidden]]:hidden"></p>
</div>
<script>
function initPhoneInputs() {
document.querySelectorAll<HTMLElement>("[data-haze-phone-input]").forEach(root => {
if (root.hasAttribute("data-enhanced")) return;
const field = root.querySelector<HTMLInputElement>("[data-phone-number]");
const countries = root.querySelector<HTMLSelectElement>("[data-phone-country]");
const normalized = root.querySelector<HTMLInputElement>("[data-phone-normalized]");
const hint = root.querySelector<HTMLElement>("[data-phone-hint]");
const error = root.querySelector<HTMLElement>("[data-phone-error]");
if (!field || !countries || !normalized || !hint || !error) return;
root.setAttribute("data-enhanced", "");
const originalName = field.name;
const label = root.querySelector("label")?.textContent ?? "Phone number";
field.name = `${originalName}-national`;
normalized.disabled = field.disabled;
const options = Array.from(countries.options);
const trigger = root.querySelector<HTMLButtonElement>("[data-phone-trigger]");
const triggerText = root.querySelector<HTMLElement>("[data-phone-trigger-text]");
const list = root.querySelector<HTMLElement>("[data-phone-list]");
const rows = Array.from(root.querySelectorAll<HTMLElement>("[data-option-code]"));
const paint = () => {
const current = countries.selectedOptions[0];
if (!current || !trigger || !triggerText) return;
const text = `${current.value} +${current.dataset.dialCode}`;
if (triggerText.textContent !== text) triggerText.textContent = text;
// Starts with the visible text (label in name), then says what it is.
trigger.setAttribute("aria-label", `${text}, ${current.dataset.name}, ${label} country calling code`);
rows.forEach(row => row.setAttribute("aria-selected", String(row.dataset.optionCode === current.value)));
};
let touched = false;
const sync = (detectCountry = false) => {
const digits = field.value.replace(/\D/g, "");
const international = field.value.trim().startsWith("+");
if (detectCountry && international) {
const match = options.filter(option => digits.startsWith(option.dataset.dialCode ?? "!")).sort((a, b) => (b.dataset.dialCode?.length ?? 0) - (a.dataset.dialCode?.length ?? 0))[0];
if (match) countries.value = match.value;
}
const code = countries.selectedOptions[0]?.dataset.dialCode ?? "";
const national = code === "1" ? digits : digits.replace(/^0+/, "");
const value = digits ? international ? `+${digits}` : `+${code}${national}` : "";
const plausible = /^\+[1-9]\d{6,14}$/.test(value);
normalized.value = value;
hint.textContent = value ? `International format: ${value}` : "Include an area code. International numbers may start with +.";
const invalid = Boolean(field.value.trim()) && (!plausible || !/^\+?[\d\s().-]*$/.test(field.value.trim()));
field.setCustomValidity(invalid ? "Enter a phone number with 7–15 digits, including the country calling code." : "");
field.setAttribute("aria-invalid", String(touched && invalid));
error.hidden = !touched || !invalid;
error.textContent = invalid ? "Check the number: use 7–15 digits including the country code." : "";
paint();
root.dispatchEvent(new CustomEvent("haze:phone-change", { bubbles: true, detail: { value, country: countries.value, plausible } }));
};
field.addEventListener("input", () => sync(true));
field.addEventListener("blur", () => { touched = true; sync(); });
countries.addEventListener("change", () => {
if (field.value.trim().startsWith("+")) {
const digits = field.value.replace(/\D/g, "");
const previous = options.filter(option => digits.startsWith(option.dataset.dialCode ?? "!")).sort((a, b) => (b.dataset.dialCode?.length ?? 0) - (a.dataset.dialCode?.length ?? 0))[0];
if (previous) field.value = digits.slice(previous.dataset.dialCode?.length ?? 0);
}
sync();
});
field.form?.addEventListener("reset", () => queueMicrotask(() => { touched = false; sync(); }));
new MutationObserver(() => { normalized.disabled = field.disabled; }).observe(field, { attributes: true, attributeFilter: ["disabled"] });
if (trigger && list) {
const choose = (row: HTMLElement) => {
countries.value = row.dataset.optionCode ?? countries.value;
countries.dispatchEvent(new Event("change", { bubbles: true }));
list.hidePopover();
trigger.focus();
};
list.addEventListener("toggle", event => {
const open = (event as ToggleEvent).newState === "open";
trigger.setAttribute("aria-expanded", String(open));
if (open) (rows.find(row => row.getAttribute("aria-selected") === "true") ?? rows[0])?.focus();
});
trigger.addEventListener("keydown", event => {
if (event.key === "ArrowDown" || event.key === "ArrowUp") { event.preventDefault(); list.showPopover(); }
});
let buffer = "";
let timer = 0;
list.addEventListener("keydown", event => {
const at = rows.indexOf(document.activeElement as HTMLElement);
const go = (index: number) => { event.preventDefault(); rows[(index + rows.length) % rows.length]?.focus(); };
if (event.key === "ArrowDown") go(at + 1);
else if (event.key === "ArrowUp") go(at - 1);
else if (event.key === "Home") go(0);
else if (event.key === "End") go(rows.length - 1);
else if ((event.key === "Enter" || event.key === " ") && at >= 0) { event.preventDefault(); choose(rows[at]); }
else if (event.key.length === 1 && !event.ctrlKey && !event.metaKey && event.key !== " ") {
buffer += event.key.toLocaleLowerCase();
clearTimeout(timer);
timer = window.setTimeout(() => { buffer = ""; }, 600);
const hit = rows.find(row => (row.dataset.optionName ?? "").toLocaleLowerCase().startsWith(buffer));
if (hit) { event.preventDefault(); hit.focus(); }
}
});
rows.forEach(row => row.addEventListener("click", () => choose(row)));
new MutationObserver(() => { trigger.disabled = countries.disabled; }).observe(countries, { attributes: true, attributeFilter: ["disabled"] });
}
sync(true);
});
}
initPhoneInputs();
if (!document.documentElement.hasAttribute("data-haze-phone-input-listener")) {
document.documentElement.setAttribute("data-haze-phone-input-listener", "");
document.addEventListener("astro:page-load", initPhoneInputs);
}
</script>When to use
- A contact form collects a country code alongside a phone number
- The host needs an international-format value while keeping the entered text visible
When not to use
- Use input with type tel when a separate country picker adds no value
- Do not use length plausibility as proof of a reachable or valid national phone number
Installation
Add the Haze registry to components.json once, then install Phone input with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/phone-inputnpx shadcn@latest add @haze/phone-inputyarn dlx shadcn@latest add @haze/phone-inputbunx --bun shadcn@latest add @haze/phone-inputFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| id* | string | – | Unique caller-supplied prefix for this component and its related elements. |
| name | string | id | Form submission name. |
| label | string | "Phone number" | Visible telephone field label. |
| country | string | "GB" | Initial country code from the supplied list. |
| countries | { code: string; label: string; dialCode: string }[] | GB, US, BA and DE | Caller-owned country choices; calling codes contain digits only. |
| value | string | "" | Initial telephone text. |
| required | boolean | – | Requires a number using native validation. |
| disabled | boolean | – | Disables the native control and its enhancement. |
| class | string | – | Additional classes for the component root. |
| ...attributes | native control attributes | – | Other attributes are forwarded to the real form control. |
Keyboard interactions
- Tab, arrow keys
- Choose the country with its native select, then type in the telephone field.
Accessibility
- Both the country select and telephone input have accessible names and retain native keyboard interaction.
- Enhanced submission uses name for the normalized value, name-national for entered text and name-country for the country code.
- Feedback checks only international syntax and 7–15 digits; verify real numbering rules in the host.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI component "Phone input" with `npx shadcn@latest add @haze/phone-input`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import PhoneInput from "@/components/haze/ui/phone-input.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: http://localhost:4329/ui/phone-input.md
Customize with real content
Adapt the Haze phone-input ui for our product. Replace the demo values of these props with our real content: id, name, label, country, countries, value, required, disabled, class, ...attributes. Keep the layout, the heading level rules and these accessibility details: Both the country select and telephone input have accessible names and retain native keyboard interaction. Enhanced submission uses name for the normalized value, name-national for entered text and name-country for the country code. Feedback checks only international syntax and 7–15 digits; verify real numbering rules in the host. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using phone-input, check it fits: use it when a contact form collects a country code alongside a phone number; the host needs an international-format value while keeping the entered text visible. Avoid it when use input with type tel when a separate country picker adds no value; do not use length plausibility as proof of a reachable or valid national phone number. Alternatives: @haze/input, @haze/input-group.
Dependencies
- npm: @lucide/astro
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.