or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

customization.mdframework-integrations.mdindex.mdinput-components.mdinternationalization.mdphone-input-components.mdutility-functions.md

utility-functions.mddocs/

0

# Utility Functions

1

2

Comprehensive phone number parsing, formatting, and validation utilities powered by libphonenumber-js. These functions provide the core phone number processing capabilities used throughout the component library and are available for standalone use.

3

4

## Capabilities

5

6

### Phone Number Formatting

7

8

Functions for formatting phone numbers in different display formats.

9

10

```typescript { .api }

11

/**

12

* Format phone number in national format for display

13

* @param value - Phone number in E.164 format or string

14

* @returns Formatted phone number for national display (e.g., "(213) 373-4253")

15

*/

16

function formatPhoneNumber(value: string): string;

17

18

/**

19

* Format phone number in international format for display

20

* @param value - Phone number in E.164 format or string

21

* @returns Formatted phone number for international display (e.g., "+1 213 373 4253")

22

*/

23

function formatPhoneNumberIntl(value: string): string;

24

```

25

26

**Usage Examples:**

27

28

```typescript

29

import { formatPhoneNumber, formatPhoneNumberIntl } from "react-phone-number-input";

30

31

// Format for national display

32

const nationalFormat = formatPhoneNumber("+12133734253");

33

console.log(nationalFormat); // "(213) 373-4253"

34

35

// Format for international display

36

const intlFormat = formatPhoneNumberIntl("+12133734253");

37

console.log(intlFormat); // "+1 213 373 4253"

38

39

// Handle undefined/invalid values

40

const invalidFormat = formatPhoneNumber("");

41

console.log(invalidFormat); // "" (empty string)

42

43

const undefinedFormat = formatPhoneNumber(undefined);

44

console.log(undefinedFormat); // "" (empty string)

45

```

46

47

### Core Variant Formatting

48

49

Core variants require manual metadata parameter for smaller bundle sizes.

50

51

```typescript { .api }

52

/**

53

* Format phone number in national format (core version)

54

* @param value - Phone number in E.164 format or string

55

* @param metadata - libphonenumber-js metadata object

56

* @returns Formatted phone number for national display

57

*/

58

function formatPhoneNumber(value: string, metadata: Metadata): string;

59

60

/**

61

* Format phone number in international format (core version)

62

* @param value - Phone number in E.164 format or string

63

* @param metadata - libphonenumber-js metadata object

64

* @returns Formatted phone number for international display

65

*/

66

function formatPhoneNumberIntl(value: string, metadata: Metadata): string;

67

```

68

69

**Core Usage Example:**

70

71

```typescript

72

import { formatPhoneNumber, formatPhoneNumberIntl } from "react-phone-number-input/core";

73

import metadata from "libphonenumber-js/metadata.json";

74

75

const nationalFormat = formatPhoneNumber("+12133734253", metadata);

76

const intlFormat = formatPhoneNumberIntl("+12133734253", metadata);

77

```

78

79

### Phone Number Parsing

80

81

Parse and extract information from phone number strings.

82

83

```typescript { .api }

84

/**

85

* Parse phone number string into PhoneNumber object

86

* @param input - Phone number string in any format

87

* @param defaultCountry - Default country for national numbers (optional)

88

* @returns PhoneNumber object or undefined if invalid

89

*/

90

function parsePhoneNumber(input: string, defaultCountry?: Country): PhoneNumber | undefined;

91

92

/**

93

* PhoneNumber class with parsed phone number information

94

*/

95

declare class PhoneNumber {

96

/** Country code (e.g., "US") */

97

country?: Country;

98

/** Country calling code (e.g., "1") */

99

countryCallingCode: string;

100

/** National number without country code */

101

nationalNumber: string;

102

/** Full number in E.164 format */

103

number: string;

104

/** Check if number is possible */

105

isPossible(): boolean;

106

/** Check if number is valid */

107

isValid(): boolean;

108

/** Format number in specified format */

109

format(format: 'E164' | 'INTERNATIONAL' | 'NATIONAL' | 'RFC3966'): string;

110

/** Get formatted number for URI (tel: links) */

111

getURI(): string;

112

/** Get possible countries for this number */

113

getPossibleCountries(): Country[];

114

}

115

```

116

117

**Parsing Examples:**

118

119

```typescript

120

import { parsePhoneNumber } from "react-phone-number-input";

121

122

// Parse international number

123

const parsed1 = parsePhoneNumber("+12133734253");

124

console.log(parsed1?.country); // "US"

125

console.log(parsed1?.nationalNumber); // "2133734253"

126

console.log(parsed1?.number); // "+12133734253"

127

128

// Parse national number with default country

129

const parsed2 = parsePhoneNumber("(213) 373-4253", "US");

130

console.log(parsed2?.number); // "+12133734253"

131

132

// Handle invalid numbers

133

const parsed3 = parsePhoneNumber("invalid");

134

console.log(parsed3); // undefined

135

136

// Check validity

137

const phoneNumber = parsePhoneNumber("+12133734253");

138

if (phoneNumber) {

139

console.log(phoneNumber.isValid()); // true

140

console.log(phoneNumber.isPossible()); // true

141

console.log(phoneNumber.format('NATIONAL')); // "(213) 373-4253"

142

console.log(phoneNumber.format('INTERNATIONAL')); // "+1 213 373 4253"

143

}

144

```

145

146

### Phone Number Validation

147

148

Functions for validating phone number correctness.

149

150

```typescript { .api }

151

/**

152

* Check if phone number is valid

153

* @param input - Phone number string in any format

154

* @param defaultCountry - Default country for national numbers (optional)

155

* @returns true if phone number is valid, false otherwise

156

*/

157

function isValidPhoneNumber(input: string, defaultCountry?: Country): boolean;

158

159

/**

160

* Check if phone number is possible (less strict than valid)

161

* @param input - Phone number string in any format

162

* @param defaultCountry - Default country for national numbers (optional)

163

* @returns true if phone number format is possible, false otherwise

164

*/

165

function isPossiblePhoneNumber(input: string, defaultCountry?: Country): boolean;

166

```

167

168

**Validation Examples:**

169

170

```typescript

171

import { isValidPhoneNumber, isPossiblePhoneNumber } from "react-phone-number-input";

172

173

// Validate international numbers

174

console.log(isValidPhoneNumber("+12133734253")); // true

175

console.log(isValidPhoneNumber("+1213373425")); // false (too short)

176

177

// Validate national numbers with default country

178

console.log(isValidPhoneNumber("(213) 373-4253", "US")); // true

179

console.log(isValidPhoneNumber("213-373-4253", "US")); // true

180

181

// Check if number format is possible

182

console.log(isPossiblePhoneNumber("+19999999999")); // true (possible format)

183

console.log(isPossiblePhoneNumber("123")); // false (too short)

184

185

// Validation in form handling

186

function validatePhoneNumber(value: string): string | boolean {

187

if (!value) return "Phone number is required";

188

if (!isValidPhoneNumber(value)) return "Please enter a valid phone number";

189

return true;

190

}

191

```

192

193

### Country Information Functions

194

195

Functions for working with country codes and calling codes.

196

197

```typescript { .api }

198

/**

199

* Get list of all supported country codes

200

* @returns Array of two-letter country codes

201

*/

202

function getCountries(): Country[];

203

204

/**

205

* Get country calling code for a country

206

* @param country - Two-letter country code

207

* @returns Country calling code as string

208

*/

209

function getCountryCallingCode(country: Country): string;

210

211

/**

212

* Check if country is supported by the library

213

* @param country - Two-letter country code to check

214

* @returns true if country is supported, false otherwise

215

*/

216

function isSupportedCountry(country: Country): boolean;

217

```

218

219

**Country Functions Examples:**

220

221

```typescript

222

import {

223

getCountries,

224

getCountryCallingCode,

225

isSupportedCountry

226

} from "react-phone-number-input";

227

228

// Get all supported countries

229

const countries = getCountries();

230

console.log(countries); // ["AD", "AE", "AF", "AG", ...]

231

console.log(countries.length); // ~250 countries

232

233

// Get calling codes

234

console.log(getCountryCallingCode("US")); // "1"

235

console.log(getCountryCallingCode("GB")); // "44"

236

console.log(getCountryCallingCode("DE")); // "49"

237

238

// Check country support

239

console.log(isSupportedCountry("US")); // true

240

console.log(isSupportedCountry("XX")); // false

241

242

// Build custom country selector

243

function buildCountryOptions(labels: Record<string, string>) {

244

return getCountries().map(country => ({

245

value: country,

246

label: `${labels[country]} +${getCountryCallingCode(country)}`,

247

supported: isSupportedCountry(country)

248

}));

249

}

250

```

251

252

### Error Handling

253

254

Utility functions handle various error conditions gracefully.

255

256

```typescript { .api }

257

// Error handling patterns for utility functions

258

259

// Formatting functions return empty string for invalid input

260

formatPhoneNumber("") // returns ""

261

formatPhoneNumber(null) // returns ""

262

formatPhoneNumber(undefined) // returns ""

263

264

// Parsing returns undefined for invalid input

265

parsePhoneNumber("invalid") // returns undefined

266

parsePhoneNumber("") // returns undefined

267

268

// Validation returns false for invalid input

269

isValidPhoneNumber("") // returns false

270

isValidPhoneNumber("invalid") // returns false

271

272

// Country functions handle invalid input

273

getCountryCallingCode("XX") // throws error for unsupported country

274

isSupportedCountry("XX") // returns false (safe check)

275

```

276

277

**Safe Error Handling Examples:**

278

279

```typescript

280

// Safe formatting with fallbacks

281

function safeFormatPhoneNumber(value: string): string {

282

try {

283

return formatPhoneNumber(value) || value;

284

} catch (error) {

285

return value; // Return original value if formatting fails

286

}

287

}

288

289

// Safe parsing with validation

290

function safeParsePhoneNumber(input: string, defaultCountry?: Country) {

291

if (!input || typeof input !== 'string') return undefined;

292

293

try {

294

return parsePhoneNumber(input, defaultCountry);

295

} catch (error) {

296

console.warn('Phone number parsing failed:', error);

297

return undefined;

298

}

299

}

300

301

// Safe country code lookup

302

function safeGetCountryCallingCode(country: Country): string | undefined {

303

if (!isSupportedCountry(country)) return undefined;

304

305

try {

306

return getCountryCallingCode(country);

307

} catch (error) {

308

return undefined;

309

}

310

}

311

```

312

313

### Custom Country Selection

314

315

Utility functions enable building custom country selection components.

316

317

```typescript { .api }

318

// Helper types for custom country selection

319

type CountryOption = {

320

value: Country;

321

label: string;

322

callingCode: string;

323

};

324

325

// Build country options with calling codes

326

function buildCountryOptions(labels: Record<Country, string>): CountryOption[] {

327

return getCountries()

328

.filter(country => isSupportedCountry(country))

329

.map(country => ({

330

value: country,

331

label: labels[country] || country,

332

callingCode: getCountryCallingCode(country)

333

}))

334

.sort((a, b) => a.label.localeCompare(b.label));

335

}

336

```

337

338

**Custom Country Select Example:**

339

340

```typescript

341

import React from "react";

342

import { getCountries, getCountryCallingCode } from "react-phone-number-input";

343

import en from "react-phone-number-input/locale/en.json";

344

345

function CustomCountrySelect({ value, onChange, ...rest }) {

346

const countries = getCountries();

347

348

return (

349

<select

350

{...rest}

351

value={value || ""}

352

onChange={e => onChange(e.target.value || undefined)}

353

>

354

<option value="">{en.ZZ}</option>

355

{countries.map(country => (

356

<option key={country} value={country}>

357

{en[country]} +{getCountryCallingCode(country)}

358

</option>

359

))}

360

</select>

361

);

362

}

363

```