diff --git a/packages/falso/src/lib/phone-number.ts b/packages/falso/src/lib/phone-number.ts index 9ab9cac48..08026decb 100644 --- a/packages/falso/src/lib/phone-number.ts +++ b/packages/falso/src/lib/phone-number.ts @@ -269,8 +269,11 @@ export function randPhoneNumber( const generateValidPhoneNumber = (): string => { let validNumber: string | null = null; + const maxRetries = 100; // Set a limit to prevent infinite loops + let attempts = 0; - while (!validNumber) { + while (!validNumber && attempts < maxRetries) { + attempts++; const phoneNumber = randMask({ mask: randElement(formats), }); @@ -281,6 +284,12 @@ export function randPhoneNumber( } } + if (!validNumber) { + throw new Error( + `Failed to generate a valid phone number after ${maxRetries} attempts.` + ); + } + return validNumber; }; @@ -290,3 +299,4 @@ export function randPhoneNumber( return fake(phoneNumber, options); } +