Chapter 8
Input formatting and sanitisation
Every insertion (typing, paste, IME commit) passes through this pipeline:
raw text ─► formatters (yours, in order) ─► sanitizeInput() ─► allow regex ─► maxLength cap ─► SecureBuffer
8.1 Formatters#
type TextInputFormatter = (inserted: string, ctx: { before: string; after: string }) => string;
before/after are the text around the insertion point (always empty for secret fields, so formatters can
never see a password). Built-ins:
| Formatter | Effect |
|---|---|
Formatters.allow(re) / Formatters.deny(re) |
Keep / drop characters matching re |
Formatters.digitsOnly() |
0-9 only |
Formatters.upperCase() / lowerCase() |
Case conversion |
Formatters.singleSpaces() |
No leading spaces, no runs of spaces |
Formatters.noMarkup() |
Drops <, > and backticks |
Custom example, card-number grouping:
const groupDigits: TextInputFormatter = (s, { before }) => {
let out = '';
let count = before.replace(/\D/g, '').length;
for (const ch of s.replace(/\D/g, '')) {
if (count > 0 && count % 4 === 0) out += ' ';
out += ch;
count++;
}
return out;
};
8.2 What the sanitiser always removes#
sanitizeInput() runs after your formatters and can't be disabled:
- C0/C1 control characters (keeps
\ninTextArea; tabs become spaces). - Bidirectional overrides and isolates (U+202A–U+202E, U+2066–U+2069, …), used in "Trojan Source" spoofing.
- Zero-width and invisible characters (ZWSP, ZWNJ, BOM, soft hyphen, …). ZWJ is kept so emoji sequences survive.
- Unpaired surrogates.
- Input over 20,000 characters is truncated before processing (stops huge-paste attacks).
- Then Unicode normalisation (NFC by default; NFKC for passwords).
You can call sanitizeInput(text, { multiline, allow, maxCodePoints, normalize }) yourself for other untrusted text.