Skip to content

fix(NumberInput): reject non-numeric characters as you type - #5110

Closed
freddymeta wants to merge 5 commits into
mainfrom
fix/number-input-reject-non-numeric
Closed

freddymeta wants to merge 5 commits into
mainfrom
fix/number-input-reject-non-numeric

Conversation

@freddymeta

Copy link
Copy Markdown
Contributor

What

Blocks non-numeric characters in NumberInput as you type. Letters and stray symbols are ignored at the change handler; a well-formed number (and valid in-progress states like -, 1., .5, 1e) types normally.

The bug

NumberInput recently moved from type="number" to type="text" (to render formatted display values and use custom stepper buttons instead of the native spinner — #4896). That switch dropped the browser's built-in numeric filtering: inputMode="numeric"/"decimal" only hints the mobile keyboard and restricts nothing on a physical one, and no keystroke-level guard was added to replace it. So the field visibly accepted abc until blur reverted it.

The committed numeric value was never wrong (parseNumberInput still gated onChange), but the field looked like it accepted letters — a visible regression.

The fix

Gate the change handler with a partial-number syntax check (isPartialNumber) so non-numeric text never becomes the field's value.

Deliberately looser than full parsing: it accepts in-progress states that aren't parseable on their own ('', -, 1., .5, 1e, 1e-). And it only blocks non-numeric text — a value that is a number but violates a constraint (e.g. 3.5 under isIntegerOnly) is still kept as pending input and surfaced as aria-invalid, exactly as before. Constraint feedback stays soft; only garbage is hard-blocked.

Tests

  • New rejects non-numeric characters block: alphabetic input, symbols mixed with digits, a well-formed number, valid in-progress states, and the constraint-violating-but-numeric case (must remain pending + invalid, not blocked).
  • Full suite: 118 tests pass, including the existing "preserves invalid pending text while focused" behavior.
  • build ✓ · tsc --noEmit ✓ · ESLint ✓ · check:repo ✓.

Relation to #4186

#4186 tracks a larger NumberInput refinement (which prescribes the type="text" move). This is the narrow regression fix for the current visible behavior; it doesn't preempt that work.

After NumberInput moved to type="text" for formatted display, letters and
stray symbols were visibly accepted until blur — inputMode only hints the
mobile keyboard and does not restrict a physical one, and the change moved
in no keystroke-level guard to replace what type="number" gave for free.

Gate the change handler with a partial-number syntax check so non-numeric
text never becomes the field's value. Numeric values that merely violate a
constraint (e.g. a decimal under isIntegerOnly) are deliberately still kept
as pending input and surfaced as invalid, preserving that behavior.
@vercel

vercel Bot commented Aug 16, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
astryx Ready Ready Preview Aug 24, 2026 3:16pm

Request Review

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Aug 16, 2026
@github-actions github-actions Bot added community Authored by a community contributor (not on the eng/design team) needs:code-review High-risk change (new package/component/API) — needs human code review before merge labels Aug 16, 2026
@github-actions

github-actions Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

PR Analysis Report

📚 Storybook Preview

View Storybook for this PR
GitHub Pages may take up to a minute to hydrate after deploy.

🧪 Sandbox Preview

View Sandbox for this PR
GitHub Pages may take up to a minute to hydrate after deploy.

Modified Components

NumberInput (@astryxdesign/core) · View in Storybook
Metric Before After Delta
Bundle Size (ESM) N/A N/A N/A
Lines of Code N/A 846 -
Complexity N/A Very High (181) -

Bundle Size Summary

Package Size (ESM) Size (CJS) Gzipped
@astryxdesign/core N/A 4.8KB 1.2KB

Accessibility Audit

Status: No accessibility violations detected.


Generated by PR Enrichment workflow | Storybook | Sandbox | View full report

github-actions Bot added a commit that referenced this pull request Aug 16, 2026

@cixzhang cixzhang left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The hard part here is that this is a text field with a pending cycle, so dropping the whole value fights an edit the browser has already made.

In Chromium: value 123, caret after the 1, press a then 9 — it commits 1239. On main you get 1a923, flagged invalid, committing nothing. A visible typo becomes a silently wrong number.

It also eats valid input silently. 42 pasted from a spreadsheet commits 42 on main and does nothing here; same for 1,234 and full-width 123. None reach the aria-invalid and "Invalid number" alert this field already has, so a screen reader gets nothing.

Ideally I'd like to keep that invalid-pending path rather than add a second, silent one. DateInput and TimeInput accept anything and reconcile on blur — do we want per-keystroke blocking here at all?

[Reviewed by Robohands]

// otherwise visibly accept "abc". Values that are numeric but violate a
// constraint (min/max/integer-only) are NOT blocked here: they stay as
// pending input and surface as invalid, preserving that behavior.
if (!isPartialNumber(newValue)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rejecting after the DOM edit throws the caret to the end; the next digit lands in the wrong place.

* before this control moved to `type="text"` for formatted display.
*/
function isPartialNumber(input: string): boolean {
return /^[-+]?(\d*\.?\d*)(e[-+]?\d*)?$/i.test(input);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

e, E, -e and .e all pass this; 42 , 1,234 and full-width 123 don't.

…ber"

Rejecting a non-numeric character from the change handler runs after the
browser has already applied the edit, so putting the value back leaves the
caret at the end: with the caret after the "1" in "123", typing "a" then "9"
gave "1239" where the native control gives "1923".

Cancel the edit at `beforeinput` instead, so it never happens — the field, the
caret and the undo stack are untouched. React's `onBeforeInput` is a synthetic
approximation that does not fire for every native event, so this attaches the
real listener, following the existing native-listener pattern in this file
(wheelListenerRef).

Two behaviours come with it, both matching what the native control does:

- Text that is numeric once normalized is normalized rather than discarded:
  whitespace, thousands separators and full-width digits ("42 ", "1,234",
  "123" pasted from a spreadsheet or a CJK IME) now commit instead of
  silently doing nothing.
- Malformed but numeric text ("--1") stays in the field as pending input and
  is surfaced through aria-invalid and the existing "Invalid number" alert,
  rather than being dropped on a second, silent path. Native does the same,
  via validity.badInput. The gate is therefore a character-set check, not a
  grammar: well-formedness stays with parseNumberInput.

IME composition is left alone — insertCompositionText is not cancelable, and
the committed text is checked when it arrives as a normal insert.

Verified in Chromium against the native control: 3/8 of these cases matched
before, 8/8 after.
The earlier commit on this branch inserted a helper between the docstring and
parseNumberInput, leaving the comment orphaned above an unrelated declaration.

@cixzhang cixzhang left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for coming back to this, and sorry it sat — the caret fix is right, and I checked the "as the native control does" claim rather than taking it: a real type="number" in the same page gives the same answers for 1,234, 123 and 1,5.

One thing to fix before it lands. With a Japanese IME in full-width mode, typing 123 leaves 112123123 in the field — no invalid flag, and it commits. On main you get 123, flagged, committing nothing. The change handler normalizes and re-sets the value on every composition update, so React rewrites the field mid-preedit. Reproduced twice.

Guarding the normalize while isComposing is true, and running it once on compositionend, should close it.

If you'd rather talk it through with someone, we're in Discord.

[Reviewed by Robohands]

@freddymeta

Copy link
Copy Markdown
Contributor Author

Closing this — main has answered the question underneath it, and the other way round.

The first review asked whether we want per-keystroke blocking here at all, given DateInput and TimeInput accept anything and reconcile on blur. #5450 and #5459 settle it in the code: parseNumberInput now reads typed and pasted text under the field locale, with a bounded separator alphabet and digit values derived from \p{Nd}. Parse generously, reconcile, flag with aria-invalid. This PR blocks keystrokes, which is the other design.

All three failures from the review are fixed on main, and not by this branch:

case on main today
42 and 1,234 silently eaten parsed
full-width 123 parsed
IME full-width committing 112123123 the composing keydown is guarded in NumberInput.tsx

Rebasing would mean re-litigating that decision against a parser that now handles the exact inputs this branch dropped.

Thanks for the two rounds on it — the caret finding and the IME repro were both right, and the IME one is the reason I looked at what main does instead.

@freddymeta freddymeta closed this Aug 25, 2026
@github-actions
github-actions Bot deleted the fix/number-input-reject-non-numeric branch August 26, 2026 06:13

This branch was successfully deployed

1 active deployment
Preview — 7647341c Deployed Aug 24, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Meta Open Source bot. community Authored by a community contributor (not on the eng/design team) needs:code-review High-risk change (new package/component/API) — needs human code review before merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants