Phone Format Utility: Parse and Validate US Phone Numbers
Utility to validate phone numbers (US Only), parse, or format.
``typescript
import PhoneUtil from "@nems.org/phone-utility";
// Or Import like below
// import {PhoneUtility} from "@nems/phone-utility"
let phone = "+1 (333) 555-7777";
let badPhone = "+1 (123) 123-4567";
PhoneUtil.isValidAmericanPhoneNumber(phone);
// returns true
PhoneUtil.isValidAmericanPhoneNumber(badPhone);
// returns false, Area Code cannot start with 1 and neither can telephone (first 3 digits after area code)
`
Parse a phone number into parts. Currently only supports US/Canada Phones
`typescript
import PhoneUtil, { ParsedPhone } from "@nems.org/phone-utility";
// Or Import As Below
// import {PhoneUtility} from "@nems/phone-utility"
let phone = "+1 (333) 555-7777";
PhoneUtil.parsePhone(phone);
/*
returns a ParsedPhone
{
areaCode: "333";
telephone: "5557777";
countyCode: "1";
telephoneDigitGroups: ["555", last4: "7777"];
}
*/
let phoneNoCountry = "333-555-7777";
PhoneUtil.parsePhone(phone);
/*
returns a ParsedPhone
{
areaCode: "333";
telephone: "5557777";
countyCode: "1"; // inferred as US/Canada
telephoneDigitGroups: ["555", last4: "7777"];
}
*/
`
Format phone numbers using tokens. Digits are represented as hash/pound signs (#). Other tokens are treated as literals and will render in place.
`typescript
import PhoneUtil from "@nems.org/phone-utility";
const phone = "3335557777";
PhoneUtil.formatPhoneNumber(phone, "+# (###) ###-####");
// returns "+1 (333) 555-7777"
PhoneUtil.formatPhoneNumber(phone, "+###########");
// returns "+13335557777"
PhoneUtil.formatPhoneNumber(phone, "###.###.####");
// returns "333.555.7777"
``