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:

You can call sanitizeInput(text, { multiline, allow, maxCodePoints, normalize }) yourself for other untrusted text.