Date input
A date typed in segments, day, month and year, in the order the locale writes them. Use it when people know the date and type faster than they pick: a birth date, an invoice date. To also pick from a month grid use the date picker.
Install
npx shadcn@latest add https://thrumui.dev/r/date-input.jsonAdds components/ui/date-input.tsx. Nothing else in your project changes.
import { segmentFieldClass } from "@/components/ui/date-input";Props
| Prop | Type | Default | Description |
|---|---|---|---|
value | Date | null | – | The date, when the parent holds it. Use it with onValueChange. |
defaultValue | Date | null | Default null | The date at first, when the field holds it itself. |
onValueChange | (value: Date | null) => void | – | Called with the date once day, month and year are all filled, and with null when one of them is cleared. |
min | Date | null | – | The earliest valid date. An earlier one is kept, reported and marks the field invalid. |
max | Date | null | – | The latest valid date. A later one is kept, reported and marks the field invalid. |
locale | string | Default "en-US" | Sets the order of the segments, the separators between them and the segment names read out. |
name | string | – | The field name in a form. A hidden input submits the date as 2026-12-03, or an empty string. |
size | "sm" | "md" | "lg" | Default "md" | sm is 28 pixels tall, md 32, lg 40. |
disabled | boolean | Default false | Dimmed, skipped by Tab, and cannot be changed. |
readOnly | boolean | Default false | Focusable and read out, but the keys do not change it. |
required | boolean | Default false | Sets aria-required on every segment. Check for a null value before you submit. |
invalid | boolean | Default false | Marks the field invalid for a reason of your own. A date outside min and max marks it on its own. |
sound | boolean | Default true | Play a soft tick when stepping a segment with arrow, Page Up/Down or Home/End keys, if the visitor has sound on. |
className | string | – | Extra classes for the field, merged last. It fills its container by default. |
dateError(date, min, max) | "min" | "max" | null | – | Exported helper: which limit a date breaks, for the message you show beside the field. |
Motion and sound
Motion
- The border colour fades over 150 ms when the field turns invalid.
- Reduced motion: it changes at once.
Sound
- A subtle tick when stepping a segment with ↑, ↓, Page Up, Page Down, Home or End. Typing digits is silent.
Sound is off until the visitor turns it on. Pass sound={false} to keep this component silent. How sound works
Accessibility
- The field is a group of spin buttons, one per segment, each with its value, its limits and its name in the locale's words (month, day, year).
- Name the group with aria-labelledby or aria-label, as the example does. Each segment is read as that name plus its own.
- An empty segment reads as Empty and shows a muted placeholder such as mm.
- A date outside min and max sets aria-invalid on every segment and turns the border red; point aria-describedby at your message so it is read too.
- Each segment is editable text, so a phone opens its number keyboard. Pasting is ignored.
| Keys | Action |
|---|---|
| Tab / Shift Tab | Move to the next or previous segment, then out of the field. |
| 0 to 9 | Fill the segment. It moves on once another digit could not fit: after 4 in the month, after two digits in the day, after four in the year. |
| ↑ / ↓ | Step the segment by one, round from the last value to the first. An empty year starts at the current year. |
| Page Up / Page Down | Step the segment by ten. |
| Home / End | The lowest or highest value of the segment. |
| ← / → | Move to the segment before or after. |
| Backspace / Delete | Clear the segment. Backspace on an empty segment moves to the one before. |
Source
"use client";
import { useState, type ComponentProps, type KeyboardEvent } from "react";
import { cn } from "@/lib/utils";
import { play } from "@/lib/thrum-sound";
import { compareDays, daysInMonth, isSameDay, makeDate, toISODate } from "@/components/ui/calendar";
// ---------------------------------------------------------------------------------------------------------------
// Segments, shared with the time input: a row of spin buttons inside one field.
// ---------------------------------------------------------------------------------------------------------------
export type SegmentFieldSize = "sm" | "md" | "lg";
const FIELD_SIZE: Record<SegmentFieldSize, string> = {
sm: "h-7 px-2",
md: "h-8 px-2.5",
lg: "h-10 px-3",
};
/** The classes of the field that holds the segments: an input's border, background, focus ring and invalid state. */
export function segmentFieldClass(size: SegmentFieldSize = "md"): string {
return cn(
// 16px text on phones: anything smaller makes iOS zoom the page when a segment takes focus.
"inline-flex w-full min-w-0 items-center overflow-hidden rounded-md border border-input bg-background text-base whitespace-nowrap text-foreground md:text-sm",
"transition-[border-color] duration-150 ease-out motion-reduce:transition-none",
"has-focus-visible:outline-2 has-focus-visible:-outline-offset-1 has-focus-visible:outline-ring",
"data-invalid:border-destructive data-disabled:cursor-not-allowed data-disabled:opacity-50",
FIELD_SIZE[size],
);
}
/** Moves the focus to the segment `offset` places away in the same field, if there is one. */
function focusSegment(from: HTMLElement, offset: number) {
const all = [...(from.closest("[data-segment-field]")?.querySelectorAll<HTMLElement>('[role="spinbutton"]') ?? [])];
all[all.indexOf(from) + offset]?.focus();
}
export type SegmentProps = {
/** The number in the segment, or null while it is empty. */
value: number | null;
min: number;
max: number;
/** Called with the new number, or null when the segment is cleared. */
onValueChange: (value: number | null) => void;
/** The segment's name for screen readers: "month", "hour". */
label: string;
/** Shown while the segment is empty: "mm", "yyyy". */
placeholder: string;
/** Digits to pad the number to: 2 for "07". */
pad?: number;
/** Text to show and announce instead of the number, as the AM/PM segment does. */
text?: string;
/** Typed digits fill the segment. False for a segment that takes letters, through `onLetter`. */
digits?: boolean;
/** Called with a typed letter, lower case. */
onLetter?: (letter: string) => void;
/** How far one arrow press moves. */
step?: number;
/** Where the first arrow press lands while the segment is empty. Defaults to `min`. */
start?: () => number;
disabled?: boolean;
readOnly?: boolean;
/** Tells a screen reader the value is not valid. The field around the segments shows it to the eye. */
invalid?: boolean;
required?: boolean;
/** Play a soft tick when stepping a segment with the arrow or Home/End keys, if the visitor has sound on. */
sound?: boolean;
};
/**
* One editable part of a date or time field: a spin button. Digits fill it and move on once no further digit could fit,
* ↑ and ↓ step it round, ← and → move between segments, Backspace clears it.
*/
export function Segment({ value, min, max, onValueChange, label, placeholder, pad = 2, text, digits = true, onLetter, step = 1, start, disabled = false, readOnly = false, invalid = false, required = false, sound = true }: SegmentProps) {
const [typed, setTyped] = useState("");
const editable = !disabled && !readOnly;
const span = max - min + 1;
const round = (n: number) => min + ((((n - min) % span) + span) % span);
const type = (target: HTMLElement, digit: string) => {
let next = typed + digit;
let n = Number(next);
if (n > max) {
next = digit;
n = Number(digit);
}
if (n >= min) onValueChange(n);
// Move on once another digit could only overflow: "4" in a month, "12" in an hour, four digits in a year.
if (next.length >= String(max).length || n * 10 > max) {
setTyped("");
if (n >= min) focusSegment(target, 1);
} else setTyped(next);
};
const onKeyDown = (event: KeyboardEvent<HTMLElement>) => {
const target = event.currentTarget;
const rtl = target.matches(":dir(rtl)") ? -1 : 1;
if (event.key === "ArrowLeft" || event.key === "ArrowRight") {
event.preventDefault();
focusSegment(target, (event.key === "ArrowRight" ? 1 : -1) * rtl);
return;
}
if (event.key === "Tab" || event.metaKey || event.ctrlKey || event.altKey || !editable) return;
event.preventDefault();
setTyped(event.key === "Backspace" || event.key === "Delete" ? "" : typed);
if (event.key === "ArrowUp") {
if (sound) play("tick");
onValueChange(value === null ? (start?.() ?? min) : round(value + step));
} else if (event.key === "ArrowDown") {
if (sound) play("tick");
onValueChange(value === null ? (start?.() ?? max) : round(value - step));
} else if (event.key === "PageUp") {
if (sound) play("tick");
onValueChange(value === null ? (start?.() ?? min) : round(value + step * 10));
} else if (event.key === "PageDown") {
if (sound) play("tick");
onValueChange(value === null ? (start?.() ?? max) : round(value - step * 10));
} else if (event.key === "Home") {
if (sound) play("tick");
onValueChange(min);
} else if (event.key === "End") {
if (sound) play("tick");
onValueChange(max);
} else if (event.key === "Backspace" || event.key === "Delete") {
if (value === null && !typed && event.key === "Backspace") focusSegment(target, -1);
else onValueChange(null);
} else if (digits && /^\d$/.test(event.key)) type(target, event.key);
else if (/^\p{L}$/u.test(event.key)) onLetter?.(event.key.toLowerCase());
};
const shown = typed || (text ?? (value === null ? placeholder : String(value).padStart(pad, "0")));
return (
<span
role="spinbutton"
data-slot="segment"
data-placeholder={(value === null && !typed) || undefined}
tabIndex={disabled ? -1 : 0}
aria-label={label}
aria-valuemin={min}
aria-valuemax={max}
aria-valuenow={value ?? undefined}
aria-valuetext={text ?? (value === null ? "Empty" : String(value))}
aria-disabled={disabled || undefined}
aria-readonly={readOnly || undefined}
aria-invalid={invalid || undefined}
aria-required={required || undefined}
// Editable text, so a phone shows its keyboard. Every edit is cancelled and applied through the value instead.
contentEditable={editable || undefined}
suppressContentEditableWarning
inputMode={digits ? "numeric" : "text"}
spellCheck={false}
autoCorrect="off"
enterKeyHint="next"
onKeyDown={onKeyDown}
onBeforeInput={(event) => {
event.preventDefault();
const data = (event.nativeEvent as InputEvent).data ?? "";
for (const char of data) {
if (digits && /\d/.test(char)) type(event.currentTarget, char);
else if (/\p{L}/u.test(char)) onLetter?.(char.toLowerCase());
}
}}
onPaste={(event) => event.preventDefault()}
onBlur={() => setTyped("")}
className={cn(
"rounded-sm px-0.5 text-center tabular-nums caret-transparent outline-none select-none",
"focus:bg-primary focus:text-primary-foreground data-placeholder:text-muted-foreground data-placeholder:focus:text-primary-foreground",
)}
>
{shown}
</span>
);
}
/** A segment's name in the locale's words ("month", "Monat"), or the English word where the browser has none. */
export function fieldName(locale: string, field: "year" | "month" | "day" | "hour" | "minute" | "second" | "dayPeriod"): string {
try {
return new Intl.DisplayNames(locale, { type: "dateTimeField" }).of(field) ?? field;
} catch {
return field === "dayPeriod" ? "AM/PM" : field;
}
}
// ---------------------------------------------------------------------------------------------------------------
// The date input.
// ---------------------------------------------------------------------------------------------------------------
type Parts = { year: number | null; month: number | null; day: number | null };
const partsOf = (date: Date | null | undefined): Parts => (date ? { year: date.getFullYear(), month: date.getMonth() + 1, day: date.getDate() } : { year: null, month: null, day: null });
/** "min" when the date is before `min`, "max" when it is after `max`, else null. For the message beside the field. */
export function dateError(date: Date | null | undefined, min?: Date | null, max?: Date | null): "min" | "max" | null {
if (!date) return null;
if (min && compareDays(date, min) < 0) return "min";
if (max && compareDays(date, max) > 0) return "max";
return null;
}
export type DateInputProps = Omit<ComponentProps<"div">, "defaultValue" | "onChange"> & {
/** The date, when the parent holds it. Use it with onValueChange. */
value?: Date | null;
/** The date at first, when the field holds it itself. */
defaultValue?: Date | null;
/** Called with the date once day, month and year are all filled, and with null when one is cleared. */
onValueChange?: (value: Date | null) => void;
/** The earliest valid date. An earlier one is kept and marks the field invalid. */
min?: Date | null;
/** The latest valid date. A later one is kept and marks the field invalid. */
max?: Date | null;
/** Sets the order of the segments and their separators. */
locale?: string;
/** The field name in a form. A hidden input submits the date as 2026-12-03. */
name?: string;
/** `sm` is 28 pixels tall, `md` 32, `lg` 40. */
size?: SegmentFieldSize;
disabled?: boolean;
readOnly?: boolean;
required?: boolean;
/** Mark the field invalid for a reason of your own. Out-of-range dates mark it on their own. */
invalid?: boolean;
/** Play a soft tick when stepping a segment with arrow, Page Up/Down or Home/End keys, if the visitor has sound on. */
sound?: boolean;
};
/**
* A date typed in segments: day, month and year as spin buttons, in the locale's order. Typing a digit fills a segment
* and moves on, the arrows step it. Name it with `aria-label` or `aria-labelledby`, as a group.
*/
export function DateInput({
value,
defaultValue = null,
onValueChange,
min,
max,
locale = "en-US",
name,
size = "md",
disabled = false,
readOnly = false,
required = false,
invalid = false,
sound = true,
className,
...props
}: DateInputProps) {
const [parts, setParts] = useState<Parts>(() => partsOf(value !== undefined ? value : defaultValue));
const [committed, setCommitted] = useState<Date | null>(value !== undefined ? value : defaultValue);
// A new value from the parent replaces whatever is typed. Done during render, so there is no frame with the old one.
if (value !== undefined && !isSameDay(value, committed) && !(value === null && committed === null)) {
setCommitted(value);
setParts(partsOf(value));
}
const date = committed;
const error = dateError(date, min, max);
const set = (key: keyof Parts, n: number | null) => {
const next = { ...parts, [key]: n };
// A day the month lacks (31 in April) becomes its last day once month and year are known.
if (next.day !== null && next.month !== null) next.day = Math.min(next.day, daysInMonth(next.year ?? 2000, next.month - 1));
setParts(next);
const complete = next.year !== null && next.month !== null && next.day !== null ? makeDate(next.year, next.month - 1, next.day) : null;
if (isSameDay(complete, committed) || (complete === null && committed === null)) return;
setCommitted(complete);
onValueChange?.(complete);
};
const order = new Intl.DateTimeFormat(locale, { year: "numeric", month: "2-digit", day: "2-digit" }).formatToParts(makeDate(2026, 10, 22));
const common = { disabled, readOnly, invalid: invalid || error !== null, required, sound };
return (
<div
role="group"
data-slot="date-input"
data-surface="control"
data-segment-field=""
data-disabled={disabled || undefined}
data-invalid={invalid || error !== null || undefined}
aria-disabled={disabled || undefined}
className={cn(segmentFieldClass(size), className)}
{...props}
>
{order.map((part, i) => {
if (part.type === "month") return <Segment key="month" label={fieldName(locale, "month")} placeholder="mm" value={parts.month} min={1} max={12} onValueChange={(n) => set("month", n)} {...common} />;
if (part.type === "day") {
const last = parts.month === null ? 31 : daysInMonth(parts.year ?? 2000, parts.month - 1);
return <Segment key="day" label={fieldName(locale, "day")} placeholder="dd" value={parts.day} min={1} max={last} onValueChange={(n) => set("day", n)} {...common} />;
}
if (part.type === "year")
return (
<Segment key="year" label={fieldName(locale, "year")} placeholder="yyyy" pad={4} value={parts.year} min={1} max={9999} start={() => new Date().getFullYear()} onValueChange={(n) => set("year", n)} {...common} />
);
return (
<span key={i} aria-hidden="true" className="px-px text-muted-foreground">
{part.value.trim() || part.value}
</span>
);
})}
{name && <input type="hidden" name={name} value={toISODate(date)} />}
</div>
);
}Files and dependencies
- Adds
components/ui/date-input.tsx- Packages
- None
- Brings along
- CalendarSound engine
Changelog
- 1.0.0 · 2026-12-03First release.