feat: implement formatNational utility and improve PhoneInput formatting and interaction logic

This commit is contained in:
estifanos
2026-08-20 08:47:28 +00:00
parent 0b03bc45c3
commit caa209306f
3 changed files with 61 additions and 13 deletions

View File

@@ -1,5 +1,5 @@
import { z } from 'zod';
import { getCountryCallingCode, isValidPhoneNumber, parsePhoneNumberFromString, type CountryCode } from 'libphonenumber-js';
import { AsYouType, getCountryCallingCode, isValidPhoneNumber, parsePhoneNumberFromString, type CountryCode } from 'libphonenumber-js';
/**
* Accepts any international number in E.164 (`+<country><number>`) or a
@@ -33,7 +33,8 @@ export function nextNationalDigits(text: string, prevDisplay: string): string {
/** National digits of a stored value, for display in the number box. */
export function toNationalDigits(value: string, country: CountryCode): string {
if (!value) return '';
const parsed = parsePhoneNumberFromString(value);
// `country` also resolves legacy national records ("0911223344").
const parsed = parsePhoneNumberFromString(value, country);
if (parsed) return parsed.nationalNumber;
if (value.startsWith('+')) {
const prefix = `+${getCountryCallingCode(country)}`;
@@ -54,3 +55,15 @@ export function toE164(digits: string, country: CountryCode): string {
`+${getCountryCallingCode(country)}${digits}`
);
}
/**
* Digits grouped for display ("91 122 3344"). Formatted as an international
* number with the dial code cut off: AsYouType's national mode leaves the
* number ungrouped unless the trunk prefix was typed.
*/
export function formatNational(digits: string, country: CountryCode): string {
if (!digits) return '';
const prefix = `+${getCountryCallingCode(country)}`;
const formatted = new AsYouType().input(prefix + digits);
return formatted.startsWith(prefix) ? formatted.slice(prefix.length).trimStart() : digits;
}