javascript 38 lines · 6 steps

Normalizing phone numbers with typed errors

A validator that parses free-form phone input and throws distinct error codes at each failure stage before returning clean formats.

Explained by highlit
1import { parsePhoneNumberFromString } from 'libphonenumber-js';
2 
3export class PhoneValidationError extends Error {
4 constructor(message, code) {
5 super(message);
6 this.name = 'PhoneValidationError';
7 this.code = code;
8 }
9}
10 
11export function normalizePhoneNumber(input, defaultCountry = 'US') {
12 if (typeof input !== 'string' || input.trim() === '') {
13 throw new PhoneValidationError('Phone number is required', 'EMPTY');
14 }
15 
16 const parsed = parsePhoneNumberFromString(input.trim(), defaultCountry);
17 
18 if (!parsed) {
19 throw new PhoneValidationError(
20 `Could not parse "${input}"`,
21 'UNPARSEABLE',
22 );
23 }
24 
25 if (!parsed.isValid()) {
26 throw new PhoneValidationError(
27 `"${input}" is not a valid number for ${parsed.country ?? defaultCountry}`,
28 'INVALID',
29 );
30 }
31 
32 return {
33 e164: parsed.number,
34 national: parsed.formatNational(),
35 country: parsed.country,
36 type: parsed.getType(),
37 };
38}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A custom Error subclass with a code field lets callers branch on failure type instead of parsing message strings.
  2. 2Guarding each distinct failure separately produces precise diagnostics rather than one vague error.
  3. 3Returning a normalized object of multiple formats frees callers from re-formatting the same value.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Normalizing phone numbers with typed errors — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code