validatorjs/validator.js · error · Error

ignore should be instance of a String or RegExp

Error message

ignore should be instance of a String or RegExp

What it means

isAlphanumeric(str, locale, ignore) shares the same `ignore` handling as isAlpha: truthy `ignore` must be a String or RegExp of characters to remove before testing. Any other type (number, array, non-RegExp object) throws this error.

Source

Thrown at src/lib/isAlphanumeric.js:16

import assertString from './util/assertString';
import { alphanumeric } from './alpha';

export default function isAlphanumeric(_str, locale = 'en-US', options = {}) {
  assertString(_str);

  let str = _str;
  const { ignore } = options;

  if (ignore) {
    if (ignore instanceof RegExp) {
      str = str.replace(ignore, '');
    } else if (typeof ignore === 'string') {
      str = str.replace(new RegExp(`[${ignore.replace(/[-[\]{}()*+?.,\\^$|#\\s]/g, '\\$&')}]`, 'g'), ''); // escape regex for ignore
    } else {
      throw new Error('ignore should be instance of a String or RegExp');
    }
  }

  if (locale in alphanumeric) {
    return alphanumeric[locale].test(str);
  }
  throw new Error(`Invalid locale '${locale}'`);
}

export const locales = Object.keys(alphanumeric);

View on GitHub (pinned to a79ff980ab)

Solutions

  1. Coerce to string or build a RegExp before the call
  2. Join arrays of characters into a string: chars.join('')
  3. Type-check the value (typeof === 'string' || value instanceof RegExp) before calling
  4. Align the call signature with the current version's docs in README

Example fix

// before
validator.isAlphanumeric(id, 'en-US', ['-']); // array
// after
validator.isAlphanumeric(id, 'en-US', '-');
Defensive patterns

Strategy: type-guard

Validate before calling

if (ignore != null && typeof ignore !== 'string' && !(ignore instanceof RegExp)) {
  throw new TypeError('ignore must be a string or RegExp before calling isAlphanumeric');
}

Type guard

const isIgnoreOption = (v) => v == null || typeof v === 'string' || v instanceof RegExp;

Try / catch

let result;
try { result = validator.isAlphanumeric(str, locale, ignore); }
catch (e) { if (/ignore should be/.test(e.message)) { result = validator.isAlphanumeric(str, locale); } else { throw e; } }

Prevention

When it happens

Trigger: isAlphanumeric('abc123', 'en-US', 0.5), passing an array of ignored chars, or passing a cross-realm RegExp-like object.

Common situations: Options sourced from JSON/CLI/config where types are not guaranteed; refactors that changed ignore from string to array; script tags/objects mistakenly reused as ignore arguments.

Related errors


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