← Back to Docs

Recipe: Phone number formatting + validation

Client-side E.164 normalization with real-time feedback.

Overview

This recipe strips non-digit characters, enforces a 10-digit floor, and formats output as +1 (XXX) XXX-XXXX. Invalid inputs surface a live error below the field. No external libraries required.

Code

const formatPhone = (raw: string): string => {
  const digits = raw.replace(/\D/g, "");
  if (digits.length < 10) return raw;
  const m = digits.match(/^(\d{1})(\d{3})(\d{3})(\d{4})$/);
  return m ? `+${m[1]} (${m[2]}) ${m[3]}-${m[4]}` : raw;
};

Validation

const isValid = (val: string): boolean =>
  val.replace(/\D/g, "").length >= 10;

Usage notes

  • Call formatPhone on every keystroke.
  • Show error when isValid returns false.
  • Store the raw E.164 string (+1XXXXXXXXXX) server-side.