From 85eb3d1de0bd2863d20829b24d479f6861f3fb66 Mon Sep 17 00:00:00 2001 From: HuluWZ Date: Tue, 20 Aug 2024 16:24:11 +0300 Subject: [PATCH] refactor: Improve phone number formatting logic and add isValid function --- src/index.ts | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/src/index.ts b/src/index.ts index 603ba1a..46e3497 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,13 +1,20 @@ export function formatPhone(phone: string) { - const phone_length = phone?.toString().length; - if (phone_length === 13 && phone.startsWith("+251")) { - return phone; - } else if (phone_length === 12 && phone.startsWith("251")) { - return `+${phone}`; - } else if (phone_length === 10 && ["09", "07"].includes(phone.slice(0, 2))) { - return `+251${phone.slice(1)}`; - } else if (phone_length === 9 && ["9", "7"].includes(phone.charAt(0))) { - return `+251${phone}`; + const formatted_phone = phone.replace(/[^+\d]/g, ""); + const phone_length = formatted_phone?.toString().length; + if (phone_length === 13 && formatted_phone.startsWith("+251")) { + return formatted_phone; + } else if (phone_length === 12 && formatted_phone.startsWith("251")) { + return `+${formatted_phone}`; + } else if ( + phone_length === 10 && + ["09", "07"].includes(formatted_phone.slice(0, 2)) + ) { + return `+251${formatted_phone.slice(1)}`; + } else if ( + phone_length === 9 && + ["9", "7"].includes(formatted_phone.charAt(0)) + ) { + return `+251${formatted_phone}`; } else { return "INVALID_PHONE_NUMBER"; }