Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

isValidPhoneNumber

Validates if a string is a plausible phone number. Accepts digits, optional + at the beginning, spaces, dashes, and parentheses.

Note: This is not a full validation based on the E.164 or ISO standards — it's a flexible basic format check. If strict compliance is required, consider using a dedicated library such as libphonenumber-js.

TypeScript
Copied!
1/**
2 * Validates if a string is a plausible phone number.
3 * Accepts digits, optional + at the beginning, spaces, dashes, and parentheses.
4 *
5 * @param str - The phone number string to validate.
6 * @returns True if the input is a valid phone number, false otherwise.
7 */
8export function isValidPhoneNumber(str: string): boolean {
9  return /^\+?[0-9\s\-().]{7,20}$/.test(str.trim());
10}
  • Flexible Format Recognition

    Supports a wide range of common phone number formats including spaces, dashes, parentheses, and an optional leading +.

  • No External Dependencies

    Pure regex-based validation keeps the utility lightweight and easily portable across projects.

  • Trim-Safe

    Automatically ignores leading/trailing whitespace before validation, ensuring consistent results.

  • Length-Based Sanity Check

    Enforces a sensible character count (7–20), helping filter out overly short or excessively long inputs.

Tests | Examples

TypeScript
Copied!
1test('isValidPhoneNumber - valid international and local formats', () => {
2  expect(isValidPhoneNumber('+1 234 567 8900')).toBe(true);
3  expect(isValidPhoneNumber('(123) 456-7890')).toBe(true);
4  expect(isValidPhoneNumber('123-456-7890')).toBe(true);
5  expect(isValidPhoneNumber('1234567890')).toBe(true);
6});
7
8test('isValidPhoneNumber - invalid cases', () => {
9  expect(isValidPhoneNumber('')).toBe(false);
10  expect(isValidPhoneNumber('abc123')).toBe(false);
11  expect(isValidPhoneNumber('12345')).toBe(false); // too short
12  expect(isValidPhoneNumber('+1-800-FLOWERS')).toBe(false); // contains letters
13});

Common Use Cases

  • Form Input Validation

    Validate phone numbers submitted by users during sign-up or checkout.

  • Contact Info Preprocessing

    Check plausibility before formatting or storing phone numbers in databases.

  • CRM or Lead Import

    Clean and validate raw phone number strings when importing customer or lead data.

  • Client-Side Filtering

    Prevent users from submitting clearly invalid numbers before backend validation.

Codebase: Utilities -> Validation -> isValidPhoneNumber | Yevhen Klymentiev