validatorjs/validator.js · error · Error

Invalid locale '${locale}'

Error message

Invalid locale '${locale}'

What it means

isMobilePhone(str, locale) validates phone numbers against per-locale patterns (e.g. 'en-US', 'zh-CN') or an array of such locales. A locale string not present in the phones table throws this error so misconfiguration is not silently reported as an invalid phone.

Source

Thrown at src/lib/isMobilePhone.js:212

      }
      return false;
    });
  } else if (locale in phones) {
    return phones[locale].test(str);
    // alias falsey locale as 'any'
  } else if (!locale || locale === 'any') {
    for (const key in phones) {
      // istanbul ignore else
      if (phones.hasOwnProperty(key)) {
        const phone = phones[key];
        if (phone.test(str)) {
          return true;
        }
      }
    }
    return false;
  }
  throw new Error(`Invalid locale '${locale}'`);
}

export const locales = Object.keys(phones);

View on GitHub (pinned to a79ff980ab)

Solutions

  1. Use exact keys from the module's exported locales list (export const locales = Object.keys(phones))
  2. Normalize the user's country to a supported validator locale key
  3. Check membership before calling: if (locales.includes(loc)) ... else fallback
  4. When the message shows 'undefined', find where the locale variable is lost

Example fix

// before
validator.isMobilePhone(phone, user.country); // e.g. 'US' -> throws
// after
const key = { US: 'en-US', GB: 'en-GB', FR: 'fr-FR' }[user.country];
validator.isMobilePhone(phone, key || 'en-US');
Defensive patterns

Strategy: validation

Validate before calling

import { locales as phoneLocales } from 'validator';
if (!phoneLocales.includes(locale)) locale = 'en-US';
validator.isMobilePhone(phone, locale);

Type guard

const isValidPhoneLocale = (loc) => typeof loc === 'string' && phoneLocales.includes(loc);

Try / catch

let ok;
try { ok = validator.isMobilePhone(phone, locale); }
catch (e) { if (/^Invalid locale/.test(e.message)) { ok = validator.isMobilePhone(phone, 'en-US'); } else { throw e; } }

Prevention

When it happens

Trigger: isMobilePhone('+14155552671', 'US') instead of 'en-US'; passing undefined locale; passing an array containing one bad key (older versions throw for unsupported entries depending on code path).

Common situations: Using ISO country codes from a billing database directly; locale from user settings in an unsupported region; version upgrade adding/removing keys.

Related errors


AI-assisted analysis of validatorjs/validator.js@a79ff980ab (2026-08-31). Data as JSON: /api/errors/001a610289d3ac78. Report an issue: GitHub.