▶ Random Everything - 100+ Free Generators // v2.8.5
root@generate-random:~/phone-numbers/code-examples$ _

Random Phone Number Code Examples

US-format and E.164 test numbers in PHP, JavaScript, Python, Java, C#, C++, Ruby and Go

Each example below produces the same set: a US-style number such as (201) 555-0123, the same shape with a +1 country code, a plain digit string, a batch, and a format check. The guide explains the North American numbering rules the code follows, which numbers are reserved for fiction and why storage should use E.164; each language section then shows the code and what is specific to that language. Prefer no code? The interactive Phone number generator does the same in the browser.

How a North American number is built

The North American Numbering Plan (country code +1: the US, Canada and much of the Caribbean) uses ten digits written NPA-NXX-XXXX: a three-digit area code, a three-digit exchange (central office code) and a four-digit line number. N stands for a digit from 2 to 9, which is why the examples draw both the area code and the exchange from 200–999. That gives 800 × 800 × 9,000 = 5.76 billion combinations per call.

The format rule is not the whole rule. N11 codes (211, 311 … 911) are service codes and never area codes or exchanges, area codes with 9 in the middle (N9X) are held for future expansion, and line numbers 0000–0999 are valid although the examples skip them. A number that passes the regex can still fail a real validator such as libphonenumber.

Use fictional numbers when anything might dial

Most random numbers in valid format belong to somebody. If a staging system sends an SMS, a sales tool auto-dials a seed record or a demo video shows the number, a real subscriber gets the call. NANPA reserves 555-0100 through 555-0199 in every area code for fictional use, so (201) 555-0123 is safe; generate those by fixing the exchange to 555 and drawing the line number from 100 to 199. Other countries keep their own ranges: Ofcom sets aside 07700 900000–07700 900999 (mobile) and 020 7946 0000–0999 (London) for drama in the UK. SMS APIs offer test credentials too; Twilio's accept magic numbers such as +15005550006.

Sending to random numbers also costs money: SMS pumping fraud works exactly by making an app text many numbers. Block outgoing messages from test environments to anything outside the fictional range.

E.164 for storage, national format for display

E.164 is the international form: a +, a country code of one to three digits and the national number, at most 15 digits in total, with no spaces or punctuation: +12015550123. Store and compare numbers in that form and format them only for display. Converting a national number usually drops a trunk prefix: the UK's 020 7946 0123 becomes +44 20 7946 0123. That is also why the country code cannot simply be glued in front of a US-shaped number: +44 (201) 555-0123 is not a UK number.

Parsing and validating real input belongs to Google's libphonenumber or one of its ports (libphonenumber-js, phonenumbers for Python, libphonenumber-for-php, libphonenumber-csharp, phonelib for Ruby, nyaruka/phonenumbers for Go). It knows each country's lengths and ranges; a regex does not.

Secure or non-secure random?

A phone number is not a secret, so the default generator of each language is the right tool and seeding it makes fixtures repeatable. The secret in phone flows is the one-time code sent to the number, and that code is what needs the secure source.

Common mistakes

  • Storing numbers as integers. The leading + and any leading zero (07700…) disappear. Use a string column.
  • A US-only regex on user input. ^\(\d{3}\) \d{3}-\d{4}$ rejects 201-555-0123, +1 201 555 0123 and every foreign number. Use it to check your own generator output, not customer data.
  • Ten random digits. The digits-only function can start with 0 or 1, which no NANP area code does.

Common Use Cases

  • Contact fields in seed data for CRM, customer and user tables
  • Sign-up and profile forms with phone input masks and validation
  • SMS and voice integrations in staging (Twilio, Vonage) without reaching real subscribers
  • Parser, formatter and E.164 normalization tests
  • Call-routing, VoIP and telecom software tests

Random Phone Number Code Examples in PHP

Generate random phone numbers in PHP using mt_rand() and Faker library. Covers US format, international format, country codes, and validation for testing.

<?php
// Generate random US phone number (xxx) xxx-xxxx
function randomUsPhoneNumber() {
    $areaCode = mt_rand(200, 999);
    $exchange = mt_rand(200, 999);
    $lineNumber = mt_rand(1000, 9999);
    return sprintf("(%03d) %03d-%04d", $areaCode, $exchange, $lineNumber);
}

// Generate random phone number with country code
function randomInternationalPhone($countryCode = "+1") {
    $areaCode = mt_rand(200, 999);
    $exchange = mt_rand(200, 999);
    $lineNumber = mt_rand(1000, 9999);
    return sprintf("%s (%03d) %03d-%04d", $countryCode, $areaCode, $exchange, $lineNumber);
}

// Generate phone number without formatting
function randomPhoneDigits($length = 10) {
    $phone = "";
    for ($i = 0; $i < $length; $i++) {
        $phone .= mt_rand(0, 9);
    }
    return $phone;
}

// Validate US phone number format
function isValidUsPhone($phone) {
    $pattern = "/^\(\d{3}\) \d{3}-\d{4}$/";
    return preg_match($pattern, $phone) === 1;
}

// Generate multiple phone numbers
function generatePhoneNumbers($count = 10) {
    $phones = [];
    for ($i = 0; $i < $count; $i++) {
        $phones[] = randomUsPhoneNumber();
    }
    return $phones;
}

// Using Faker library (composer require fakerphp/faker)
// require "vendor/autoload.php";
// $faker = Faker\Factory::create();
// $phone = $faker->phoneNumber(); // (555) 123-4567
// $phoneE164 = $faker->e164PhoneNumber(); // +15551234567

echo "US Phone: " . randomUsPhoneNumber() . "\n";
echo "International: " . randomInternationalPhone("+1") . "\n";
echo "Digits only: " . randomPhoneDigits(10) . "\n";
echo "Valid: " . (isValidUsPhone("(555) 123-4567") ? "true" : "false") . "\n";
echo "Batch: " . implode(", ", generatePhoneNumbers(3)) . "\n";
?>

How it works in PHP

PHP uses mt_rand() for generating area codes (200-999), exchanges (200-999), and line numbers (1000-9999). sprintf() formats with leading zeros and separators. preg_match() validates patterns. Faker library offers phoneNumber() for realistic formats and e164PhoneNumber() for international E.164 format (+15551234567). For test data, Faker generates locale-specific phone numbers.

Sample output

US Phone: (555) 234-5678
International: +1 (555) 234-5678
Digits only: 5551234567
Valid: true
Batch: (234) 567-8901, (345) 678-9012, (456) 789-0123

PHP notes

  • With giggsey/libphonenumber-for-php: $util->parse('020 7946 0123', 'GB'), then $util->format($n, PhoneNumberFormat::E164).
  • fakerphp's e164PhoneNumber() returns the + form directly; phoneNumber() follows the locale's formats, set with Factory::create('en_US').
  • preg_match() returns 1, 0, or false on a pattern error, hence the strict === 1.

Random Phone Number Code Examples in JavaScript

Generate random phone numbers in JavaScript using Math.random() and faker-js. Covers US format, international format, and validation for testing.

// Generate random US phone number (xxx) xxx-xxxx
function randomUsPhoneNumber() {
    const areaCode = Math.floor(Math.random() * 800) + 200;
    const exchange = Math.floor(Math.random() * 800) + 200;
    const lineNumber = Math.floor(Math.random() * 9000) + 1000;
    return `(${areaCode.toString().padStart(3, "0")}) ${exchange.toString().padStart(3, "0")}-${lineNumber.toString().padStart(4, "0")}`;
}

// Generate random phone number with country code
function randomInternationalPhone(countryCode = "+1") {
    const areaCode = Math.floor(Math.random() * 800) + 200;
    const exchange = Math.floor(Math.random() * 800) + 200;
    const lineNumber = Math.floor(Math.random() * 9000) + 1000;
    return `${countryCode} (${areaCode.toString().padStart(3, "0")}) ${exchange.toString().padStart(3, "0")}-${lineNumber.toString().padStart(4, "0")}`;
}

// Generate phone number without formatting
function randomPhoneDigits(length = 10) {
    return Array.from({ length }, () => Math.floor(Math.random() * 10)).join("");
}

// Validate US phone number format
function isValidUsPhone(phone) {
    const pattern = /^\(\d{3}\) \d{3}-\d{4}$/;
    return pattern.test(phone);
}

// Generate multiple phone numbers
function generatePhoneNumbers(count = 10) {
    return Array.from({ length: count }, () => randomUsPhoneNumber());
}

// Using faker-js library (npm install @faker-js/faker)
// import { faker } from "@faker-js/faker";
// const phone = faker.helpers.replaceSymbols("(###) ###-####"); // (555) 123-4567
// const phoneE164 = faker.phone.number({ style: "international" }); // +15551234567

console.log("US Phone:", randomUsPhoneNumber());
console.log("International:", randomInternationalPhone("+1"));
console.log("Digits only:", randomPhoneDigits(10));
console.log("Valid:", isValidUsPhone("(555) 123-4567"));
console.log("Batch:", generatePhoneNumbers(3).join(", "));

How it works in JavaScript

JavaScript uses Math.random() for generating area codes (200-999), exchanges (200-999), and line numbers (1000-9999). padStart() ensures leading zeros. RegExp.test() validates patterns. faker-js v9 offers faker.phone.number({ style: "international" }) for E.164 output; custom patterns such as (###) ###-#### go through faker.helpers.replaceSymbols(), where # is any digit. Array.from() with length creates arrays for batch generation. Template literals provide clean string formatting.

Sample output

US Phone: (555) 234-5678
International: +1 (555) 234-5678
Digits only: 5551234567
Valid: true
Batch: (234) 567-8901, (345) 678-9012, (456) 789-0123

JavaScript notes

  • libphonenumber-js: parsePhoneNumber('+12015550123').formatNational() and isValidPhoneNumber().
  • <input type="tel"> validates nothing; it only brings up the numeric keypad on phones. Add a pattern or validate in code.
  • In @faker-js/faker v9, faker.phone.number({ style: 'national' }) gives (959) 355-3028-style output.

Random Phone Number Code Examples in Python

Generate random phone numbers in Python using random.randint() and Faker library. Covers US format, international format, and validation for testing.

import random
import re

# Generate random US phone number (xxx) xxx-xxxx
def random_us_phone_number():
    area_code = random.randint(200, 999)
    exchange = random.randint(200, 999)
    line_number = random.randint(1000, 9999)
    return f"({area_code:03d}) {exchange:03d}-{line_number:04d}"

# Generate random phone number with country code
def random_international_phone(country_code="+1"):
    area_code = random.randint(200, 999)
    exchange = random.randint(200, 999)
    line_number = random.randint(1000, 9999)
    return f"{country_code} ({area_code:03d}) {exchange:03d}-{line_number:04d}"

# Generate phone number without formatting
def random_phone_digits(length=10):
    return "".join(str(random.randint(0, 9)) for _ in range(length))

# Validate US phone number format
def is_valid_us_phone(phone):
    pattern = r"^\(\d{3}\) \d{3}-\d{4}$"
    return re.match(pattern, phone) is not None

# Generate multiple phone numbers
def generate_phone_numbers(count=10):
    return [random_us_phone_number() for _ in range(count)]

# Using Faker library (pip install faker)
# from faker import Faker
# faker = Faker()
# phone = faker.phone_number()  # (555) 123-4567
# msisdn = faker.msisdn()       # 13 random digits, not an E.164 number

print(f"US Phone: {random_us_phone_number()}")
print(f"International: {random_international_phone('+1')}")
print(f"Digits only: {random_phone_digits(10)}")
print(f"Valid: {is_valid_us_phone('(555) 123-4567')}")
print(f"Batch: {', '.join(generate_phone_numbers(3))}")

How it works in Python

Python uses random.randint() for generating area codes (200-999), exchanges (200-999), and line numbers (1000-9999). F-string formatting with :03d ensures 3-digit zero-padding. re.match() validates patterns. Faker library offers phone_number() for locale-specific formats ; msisdn() only returns 13 random digits, not a valid E.164 number. List comprehensions provide concise batch generation.

Sample output

US Phone: (555) 234-5678
International: +1 (555) 234-5678
Digits only: 5551234567
Valid: True
Batch: (234) 567-8901, (345) 678-9012, (456) 789-0123

Python notes

  • The phonenumbers package: n = phonenumbers.parse("+12015550123"), phonenumbers.is_valid_number(n), phonenumbers.format_number(n, phonenumbers.PhoneNumberFormat.E164).
  • Faker's en_US phone_number() mixes formats, including 001-626-200-4671x9650 with an extension, so it will not pass the US regex.
  • Faker's msisdn() returns 13 random digits and is not a valid E.164 number.

Random Phone Number Code Examples in Java

Generate random phone numbers in Java using Random and JavaFaker library. Covers US format, international format, and validation for testing.

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.regex.Pattern;

public class PhoneNumberGenerator {
    private static final Random random = new Random();

    // Generate random US phone number (xxx) xxx-xxxx
    public static String randomUsPhoneNumber() {
        int areaCode = random.nextInt(800) + 200;
        int exchange = random.nextInt(800) + 200;
        int lineNumber = random.nextInt(9000) + 1000;
        return String.format("(%03d) %03d-%04d", areaCode, exchange, lineNumber);
    }

    // Generate random phone number with country code
    public static String randomInternationalPhone(String countryCode) {
        int areaCode = random.nextInt(800) + 200;
        int exchange = random.nextInt(800) + 200;
        int lineNumber = random.nextInt(9000) + 1000;
        return String.format("%s (%03d) %03d-%04d", countryCode, areaCode, exchange, lineNumber);
    }

    // Generate phone number without formatting
    public static String randomPhoneDigits(int length) {
        StringBuilder phone = new StringBuilder();
        for (int i = 0; i < length; i++) {
            phone.append(random.nextInt(10));
        }
        return phone.toString();
    }

    // Validate US phone number format
    public static boolean isValidUsPhone(String phone) {
        return Pattern.matches("^\\(\\d{3}\\) \\d{3}-\\d{4}$", phone);
    }

    // Generate multiple phone numbers
    public static List<String> generatePhoneNumbers(int count) {
        List<String> phones = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            phones.add(randomUsPhoneNumber());
        }
        return phones;
    }

    // Using JavaFaker library (Maven: com.github.javafaker:javafaker:1.0.2)
    // import com.github.javafaker.Faker;
    // Faker faker = new Faker();
    // String phone = faker.phoneNumber().phoneNumber(); // (555) 123-4567
    // String cellPhone = faker.phoneNumber().cellPhone(); // 555-123-4567

    public static void main(String[] args) {
        System.out.println("US Phone: " + randomUsPhoneNumber());
        System.out.println("International: " + randomInternationalPhone("+1"));
        System.out.println("Digits only: " + randomPhoneDigits(10));
        System.out.println("Valid: " + isValidUsPhone("(555) 123-4567"));
        System.out.println("Batch: " + String.join(", ", generatePhoneNumbers(3)));
    }
}

How it works in Java

Java uses Random.nextInt() for generating area codes (200-999), exchanges (200-999), and line numbers (1000-9999). String.format("%03d") formats with leading zeros. Pattern.matches() validates regex patterns. StringBuilder efficiently builds digit-only strings. JavaFaker library offers phoneNumber().phoneNumber() for various formats and cellPhone() for mobile numbers. ArrayList stores batch results.

Sample output

US Phone: (555) 234-5678
International: +1 (555) 234-5678
Digits only: 5551234567
Valid: true
Batch: (234) 567-8901, (345) 678-9012, (456) 789-0123

Java notes

  • Every regex backslash is doubled in a Java string literal: "^\\(\\d{3}\\)" is the pattern ^\(\d{3}\).
  • ThreadLocalRandom.current().nextInt(200, 1000) takes the origin and bound directly.
  • Google's libphonenumber (com.googlecode.libphonenumber:libphonenumber) is the reference implementation: PhoneNumberUtil.getInstance().parse(text, "US").

Random Phone Number Code Examples in C#

Generate random phone numbers in C# using Random and Bogus library. Covers US format, international format, and validation for .NET testing.

using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

public class PhoneNumberGenerator
{
    private static readonly Random random = new Random();

    // Generate random US phone number (xxx) xxx-xxxx
    public static string RandomUsPhoneNumber()
    {
        int areaCode = random.Next(200, 1000);
        int exchange = random.Next(200, 1000);
        int lineNumber = random.Next(1000, 10000);
        return $"({areaCode:D3}) {exchange:D3}-{lineNumber:D4}";
    }

    // Generate random phone number with country code
    public static string RandomInternationalPhone(string countryCode = "+1")
    {
        int areaCode = random.Next(200, 1000);
        int exchange = random.Next(200, 1000);
        int lineNumber = random.Next(1000, 10000);
        return $"{countryCode} ({areaCode:D3}) {exchange:D3}-{lineNumber:D4}";
    }

    // Generate phone number without formatting
    public static string RandomPhoneDigits(int length = 10)
    {
        var sb = new StringBuilder();
        for (int i = 0; i < length; i++)
        {
            sb.Append(random.Next(10));
        }
        return sb.ToString();
    }

    // Validate US phone number format
    public static bool IsValidUsPhone(string phone)
    {
        return Regex.IsMatch(phone, @"^\(\d{3}\) \d{3}-\d{4}$");
    }

    // Generate multiple phone numbers
    public static string[] GeneratePhoneNumbers(int count = 10)
    {
        return Enumerable.Range(0, count)
            .Select(_ => RandomUsPhoneNumber())
            .ToArray();
    }

    // Using Bogus library (Install-Package Bogus)
    // using Bogus;
    // var faker = new Faker();
    // string phone = faker.Phone.PhoneNumber("(###) ###-####"); // (555) 123-4567
    // string phoneE164 = faker.Phone.PhoneNumber("+1##########"); // +15551234567

    public static void Main()
    {
        Console.WriteLine($"US Phone: {RandomUsPhoneNumber()}");
        Console.WriteLine($"International: {RandomInternationalPhone("+1")}");
        Console.WriteLine($"Digits only: {RandomPhoneDigits(10)}");
        Console.WriteLine($"Valid: {IsValidUsPhone("(555) 123-4567")}");
        Console.WriteLine($"Batch: {string.Join(", ", GeneratePhoneNumbers(3))}");
    }
}

How it works in C#

C# uses Random.Next(200, 1000) for generating area codes (200-999), exchanges (200-999), and line numbers (1000-9999). String interpolation with :D3 format specifier ensures 3-digit zero-padding. Regex.IsMatch() validates patterns. StringBuilder efficiently builds digit-only strings. Bogus library offers Phone.PhoneNumber() with custom format strings using # for digits. LINQ's Enumerable.Range() enables functional-style batch generation.

Sample output

US Phone: (555) 234-5678
International: +1 (555) 234-5678
Digits only: 5551234567
Valid: True
Batch: (234) 567-8901, (345) 678-9012, (456) 789-0123

C# notes

  • random.Next(200, 1000) excludes 1000, so 999 is the largest value.
  • The [Phone] data annotation is very permissive: it accepts most strings of digits and separators, so it is not a format check.
  • The libphonenumber-csharp NuGet package exposes PhoneNumbers.PhoneNumberUtil.GetInstance().Parse(text, "US").

Random Phone Number Code Examples in C++

Generate random phone numbers in C++ using std::random and string formatting. Covers US format, international format, and validation.

#include <iostream>
#include <random>
#include <sstream>
#include <iomanip>
#include <vector>
#include <regex>

class PhoneNumberGenerator {
private:
    std::mt19937 rng;
    std::uniform_int_distribution<int> areaCodeDist;
    std::uniform_int_distribution<int> exchangeDist;
    std::uniform_int_distribution<int> lineNumberDist;
    std::uniform_int_distribution<int> digitDist;

public:
    PhoneNumberGenerator()
        : rng(std::random_device{}()),
          areaCodeDist(200, 999),
          exchangeDist(200, 999),
          lineNumberDist(1000, 9999),
          digitDist(0, 9) {}

    // Generate random US phone number (xxx) xxx-xxxx
    std::string randomUsPhoneNumber() {
        std::ostringstream oss;
        oss << "(" << std::setw(3) << std::setfill('0') << areaCodeDist(rng) << ") "
            << std::setw(3) << std::setfill('0') << exchangeDist(rng) << "-"
            << std::setw(4) << std::setfill('0') << lineNumberDist(rng);
        return oss.str();
    }

    // Generate random phone number with country code
    std::string randomInternationalPhone(const std::string& countryCode = "+1") {
        std::ostringstream oss;
        oss << countryCode << " (" << std::setw(3) << std::setfill('0') << areaCodeDist(rng) << ") "
            << std::setw(3) << std::setfill('0') << exchangeDist(rng) << "-"
            << std::setw(4) << std::setfill('0') << lineNumberDist(rng);
        return oss.str();
    }

    // Generate phone number without formatting
    std::string randomPhoneDigits(int length = 10) {
        std::ostringstream oss;
        for (int i = 0; i < length; ++i) {
            oss << digitDist(rng);
        }
        return oss.str();
    }

    // Validate US phone number format
    bool isValidUsPhone(const std::string& phone) {
        std::regex pattern(R"(^\(\d{3}\) \d{3}-\d{4}$)");
        return std::regex_match(phone, pattern);
    }

    // Generate multiple phone numbers
    std::vector<std::string> generatePhoneNumbers(int count = 10) {
        std::vector<std::string> phones;
        phones.reserve(count);
        for (int i = 0; i < count; ++i) {
            phones.push_back(randomUsPhoneNumber());
        }
        return phones;
    }
};

int main() {
    PhoneNumberGenerator generator;

    std::cout << "US Phone: " << generator.randomUsPhoneNumber() << std::endl;
    std::cout << "International: " << generator.randomInternationalPhone("+1") << std::endl;
    std::cout << "Digits only: " << generator.randomPhoneDigits(10) << std::endl;
    std::cout << "Valid: " << (generator.isValidUsPhone("(555) 123-4567") ? "true" : "false") << std::endl;

    auto batch = generator.generatePhoneNumbers(3);
    std::cout << "Batch: ";
    for (size_t i = 0; i < batch.size(); ++i) {
        std::cout << batch[i];
        if (i < batch.size() - 1) std::cout << ", ";
    }
    std::cout << std::endl;

    return 0;
}

How it works in C++

C++ uses std::uniform_int_distribution for generating area codes (200-999), exchanges (200-999), and line numbers (1000-9999). std::ostringstream with std::setw() and std::setfill() formats with leading zeros. std::regex_match() validates patterns. std::mt19937 provides high-quality random generation. std::vector stores batch results with reserve() for efficiency. Raw string literal R"(...)" simplifies regex patterns.

Sample output

US Phone: (555) 234-5678
International: +1 (555) 234-5678
Digits only: 5551234567
Valid: true
Batch: (234) 567-8901, (345) 678-9012, (456) 789-0123

C++ notes

  • Google's libphonenumber is itself a C++ library (alongside Java), so C++ code can call PhoneNumberUtil::GetInstance()->Parse() directly.
  • Building a std::regex is expensive: make it static instead of constructing it on every isValidUsPhone() call.
  • std::setw() applies to the next value only, so each part of the number sets it again.

Random Phone Number Code Examples in Ruby

Generate random phone numbers in Ruby using rand() and Faker gem. Covers US format, international format, and validation for Rails testing.

require "securerandom"

# Generate random US phone number (xxx) xxx-xxxx
def random_us_phone_number
  area_code = rand(200..999)
  exchange = rand(200..999)
  line_number = rand(1000..9999)
  format("(%03d) %03d-%04d", area_code, exchange, line_number)
end

# Generate random phone number with country code
def random_international_phone(country_code = "+1")
  area_code = rand(200..999)
  exchange = rand(200..999)
  line_number = rand(1000..9999)
  format("%s (%03d) %03d-%04d", country_code, area_code, exchange, line_number)
end

# Generate phone number without formatting
def random_phone_digits(length = 10)
  length.times.map { rand(0..9) }.join
end

# Validate US phone number format
def valid_us_phone?(phone)
  phone.match?(/^\(\d{3}\) \d{3}-\d{4}$/)
end

# Generate multiple phone numbers
def generate_phone_numbers(count = 10)
  Array.new(count) { random_us_phone_number }
end

# Using Faker gem (gem install faker)
# require "faker"
# phone = Faker::PhoneNumber.phone_number         # (555) 123-4567
# phone_e164 = Faker::PhoneNumber.phone_number_with_country_code  # +1 555-123-4567
# cell = Faker::PhoneNumber.cell_phone            # 555-123-4567

puts "US Phone: #{random_us_phone_number}"
puts "International: #{random_international_phone("+1")}"
puts "Digits only: #{random_phone_digits(10)}"
puts "Valid: #{valid_us_phone?("(555) 123-4567")}"
puts "Batch: #{generate_phone_numbers(3).join(", ")}"

How it works in Ruby

Ruby uses rand(200..999) for generating area codes, exchanges, and line numbers. format("%03d") or sprintf formats with leading zeros. String#match? validates regex patterns efficiently. Array.new(count) { block } creates arrays with generated values. Faker gem offers PhoneNumber.phone_number for various formats and phone_number_with_country_code for international format. Ranges and blocks provide clean, idiomatic Ruby code.

Sample output

US Phone: (555) 234-5678
International: +1 (555) 234-5678
Digits only: 5551234567
Valid: true
Batch: (234) 567-8901, (345) 678-9012, (456) 789-0123

Ruby notes

  • Faker::PhoneNumber.phone_number varies its layout (756-147-0350, 688 589 0015), so it fails valid_us_phone?; cell_phone_in_e164 returns a + form.
  • The phonelib gem wraps libphonenumber data: Phonelib.parse("+12015550123").valid? and .e164.

Random Phone Number Code Examples in Go

Generate random phone numbers in Go using math/rand and fmt package. Covers US format, international format, and validation for testing.

package main

import (
    "fmt"
    "math/rand"
    "regexp"
    "strings"
)

// Generate random US phone number (xxx) xxx-xxxx
func randomUsPhoneNumber() string {
    areaCode := rand.Intn(800) + 200
    exchange := rand.Intn(800) + 200
    lineNumber := rand.Intn(9000) + 1000
    return fmt.Sprintf("(%03d) %03d-%04d", areaCode, exchange, lineNumber)
}

// Generate random phone number with country code
func randomInternationalPhone(countryCode string) string {
    areaCode := rand.Intn(800) + 200
    exchange := rand.Intn(800) + 200
    lineNumber := rand.Intn(9000) + 1000
    return fmt.Sprintf("%s (%03d) %03d-%04d", countryCode, areaCode, exchange, lineNumber)
}

// Generate phone number without formatting
func randomPhoneDigits(length int) string {
    var sb strings.Builder
    for i := 0; i < length; i++ {
        sb.WriteString(fmt.Sprintf("%d", rand.Intn(10)))
    }
    return sb.String()
}

// Validate US phone number format
func isValidUsPhone(phone string) bool {
    pattern := `^\(\d{3}\) \d{3}-\d{4}$`
    matched, _ := regexp.MatchString(pattern, phone)
    return matched
}

// Generate multiple phone numbers
func generatePhoneNumbers(count int) []string {
    phones := make([]string, count)
    for i := 0; i < count; i++ {
        phones[i] = randomUsPhoneNumber()
    }
    return phones
}

func main() {
    fmt.Println("US Phone:", randomUsPhoneNumber())
    fmt.Println("International:", randomInternationalPhone("+1"))
    fmt.Println("Digits only:", randomPhoneDigits(10))
    fmt.Println("Valid:", isValidUsPhone("(555) 123-4567"))
    fmt.Println("Batch:", strings.Join(generatePhoneNumbers(3), ", "))
}

How it works in Go

Go uses rand.Intn() for generating area codes (200-999), exchanges (200-999), and line numbers (1000-9999). fmt.Sprintf("%03d") formats with leading zeros. regexp.MatchString() validates patterns. strings.Builder efficiently builds digit-only strings. make([]string, count) pre-allocates slices. strings.Join() concatenates with separators. Since Go 1.20 the global source is seeded automatically, so no rand.Seed call is needed.

Sample output

US Phone: (555) 234-5678
International: +1 (555) 234-5678
Digits only: 5551234567
Valid: true
Batch: (234) 567-8901, (345) 678-9012, (456) 789-0123

Go notes

  • github.com/nyaruka/phonenumbers ports libphonenumber: phonenumbers.Parse(s, "US"), then phonenumbers.Format(n, phonenumbers.E164).
  • Compile the pattern once with regexp.MustCompile at package level; regexp.MatchString recompiles it on every call.
  • sb.WriteByte(byte('0' + rand.Intn(10))) avoids the allocation of fmt.Sprintf for each digit.

Try the Interactive Generator

Need values right now rather than code? The Phone number generator runs in the browser and exports to TXT, CSV or JSON.

OPEN THE PHONE NUMBER GENERATOR →