phone-number-generator-js
Version:
Generates a random phone number following the E.164 international standard
56 lines (55 loc) • 2.64 kB
JavaScript
import { isValidNumberForRegion, isValidPhoneNumber } from "libphonenumber-js";
import { isPhoneNumber } from 'class-validator';
import { random, sample } from "lodash";
import { countryPhoneDataArray } from "./countryPhoneData";
export default function generatePhoneNumber(config) {
for (var i = 0; i < 100; i++) {
var countryPhoneData = getCountryPhoneDataByConfig(config);
for (var j = 0; j < 1000; j++) {
var phoneNumber = getRandomPhoneNumber(countryPhoneData, config === null || config === void 0 ? void 0 : config.withoutCountryCode);
if (isPhoneNumberValid(phoneNumber, countryPhoneData, config === null || config === void 0 ? void 0 : config.withoutCountryCode)) {
return phoneNumber;
}
}
if (config) {
break;
}
}
throw new Error("Failed to generate phone number");
}
export function isPhoneNumberValid(phoneNumber, countryPhoneData, withoutCountryCode) {
if (withoutCountryCode) {
return countryPhoneData !== undefined && isValidNumberForRegion(phoneNumber, countryPhoneData.alpha2);
}
return isValidPhoneNumber(phoneNumber) && isPhoneNumber(phoneNumber);
}
function getRandomPhoneNumber(countryPhoneData, withoutCountryCode) {
var _a;
if (withoutCountryCode === void 0) { withoutCountryCode = false; }
var randomMobileBeginWith = (_a = sample(countryPhoneData.mobile_begin_with)) !== null && _a !== void 0 ? _a : "";
var randomPhoneNumberSuffix = getRandomPhoneNumberSuffix(countryPhoneData.phone_number_lengths[0] - randomMobileBeginWith.length);
return "" + (withoutCountryCode ? '' : '+' + countryPhoneData.country_code) + randomMobileBeginWith + randomPhoneNumberSuffix;
}
function getRandomPhoneNumberSuffix(phoneNumberLength) {
return "" + random(2, 10) + getRandomNumberInLength(phoneNumberLength - 1);
}
function getRandomNumberInLength(length) {
var min = Math.pow(10, length - 1);
var max = Math.pow(10, length) - 1;
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function getCountryPhoneDataByConfig(config) {
var _a;
if (config === void 0) { config = {}; }
var countryPhoneData;
if (!config || !config.countryName) {
countryPhoneData = sample(countryPhoneDataArray);
}
else {
countryPhoneData =
(_a = countryPhoneDataArray.find(function (countryPhoneData) { return countryPhoneData.country_name === config.countryName; })) !== null && _a !== void 0 ? _a : (function () {
throw new Error("Invalid country name");
})();
}
return countryPhoneData;
}