Skip to content

Commit

Permalink
refactor: Improve phone number formatting logic and add isValid function
Browse files Browse the repository at this point in the history
  • Loading branch information
HuluWZ committed Aug 20, 2024
1 parent 6aeb229 commit 85eb3d1
Showing 1 changed file with 16 additions and 9 deletions.
25 changes: 16 additions & 9 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -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";
}
Expand Down

0 comments on commit 85eb3d1

Please sign in to comment.