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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A custom Error subclass with a code field lets callers branch on failure type instead of parsing message strings.
- 2Guarding each distinct failure separately produces precise diagnostics rather than one vague error.
- 3Returning a normalized object of multiple formats frees callers from re-formatting the same value.
Related explainers
typescript
import { Injectable, computed, inject, signal } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { firstValueFrom } from 'rxjs';
Optimistic updates with Angular signals
signals
optimistic-updates
state-management
Intermediate
9 steps
python
import os from datetime import datetime, timezone import jwt
JWT bearer auth as a FastAPI dependency
authentication
jwt
dependency-injection
Intermediate
7 steps
rust
use std::error::Error; use std::path::Path; use serde::Deserialize;
Custom CSV deserialization with serde in Rust
serde
csv
deserialization
Intermediate
7 steps
go
package config import ( "fmt"
Loading typed config from environment variables in Go
configuration
environment-variables
type-parsing
Beginner
8 steps
php
public function importCustomers(UploadedFile $file): array { $errors = []; $imported = 0;
Validating a CSV import in Laravel
csv-parsing
validation
error-accumulation
Intermediate
8 steps
javascript
const express = require('express'); const { z } = require('zod'); const router = express.Router();
Validating query params with Zod in Express
validation
schema-parsing
query-building
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/normalizing-phone-numbers-with-typed-errors-explained-javascript-1864/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.