Validate strings with class-validator Matches

How the class-validator Matches decorator tests strings against a regular expression, what it does and does not change, Unicode pitfalls, and when a dedicated validator fits better.

The Matches decorator in class-validator checks whether a string property fits a regular expression. It is the general-purpose regex tool in a library that otherwise offers many narrow validators, such as checks for emails, UUIDs or alphanumeric text. This review covers what Matches does, where it fits, and where a plain dedicated validator or extra preprocessing is the safer choice.

Is Matches suitable for your use?

Matches is a good fit when a field follows a format you can describe precisely and that no built-in validator already covers. Examples include internal identifiers, SKU codes, slugs and constrained usernames. Its main benefit is flexibility: any pattern JavaScript's RegExp engine accepts can become a validation rule attached directly to a DTO or class property.

The main tradeoff is that you own the correctness of the pattern. A dedicated validator such as IsEmail or IsUUID encodes a maintained definition of the format. A hand-written regex encodes only what you remembered to include. Regex patterns are also easy to get subtly wrong, especially with anchoring, Unicode and performance.

Prefer a built-in validator when one exists for the format. Prefer a custom validator when the rule depends on other fields, external data or logic that a regex expresses poorly, such as checksums or date ranges.

What Matches actually changes

Matches changes nothing about the value. It does not trim, normalize, reverse, restyle or rewrite the string. It only reports whether the value passes the test. If the value is not a string, validation fails rather than coercing it. This matters when input arrives as a number, for example a numeric code parsed from JSON.

Any transformation has to happen separately and before validation. Typical examples are trimming whitespace, lowercasing or Unicode normalization. In practice, this is usually done with class-transformer decorators or framework pipes. Be explicit about the order in which these steps run, because the regex sees only the value as it exists at validation time.

Basic usage

The decorator takes a pattern and an optional options object. The patterns below are illustrations, not recommended production rules.

import { IsOptional, Matches } from 'class-validator';

export class CreateAccountDto {
  @Matches(/^[a-z0-9_]{3,20}$/, {
    message: 'username must be 3-20 lowercase letters, digits or underscores',
  })
  username: string;

  @IsOptional()
  @Matches(/^[A-Z]{2}-[0-9]{4}$/)
  referenceCode?: string;
}

The pattern can also be passed as a string, with the regex flags as a separate second argument. The library additionally exports a standalone matches function for checks outside decorated classes.

import { Matches, matches } from 'class-validator';

class CountryInput {
  @Matches('^[a-z]{2}$', 'i')
  country: string;
}

matches('US', /^[A-Z]{2}$/); // true

Options worth knowing

  • message: replaces the generic default error text, which exposes the raw pattern and is rarely user-friendly.
  • each: when the property is an array, applies the pattern to every element.
  • groups and always: control which validation groups the rule participates in.
  • context: attaches arbitrary data to the validation error for downstream handling.

Common pattern mistakes

  • Missing anchors: without ^ and $, the pattern only needs to match somewhere in the string. For example, /[0-9]{4}/ accepts 'abc12345xyz'.
  • Optional fields: Matches fails on undefined or null. Add IsOptional if the field may be absent.
  • Case handling: use the i flag, or an explicit character class, rather than assuming input case.
  • Catastrophic backtracking: nested quantifiers such as (a+)+ can make validation very slow on crafted input. Keep patterns simple and bound input length, for example with MaxLength.

Unicode, pasted text and readability of results

Because Matches tests the exact code points it receives, text copied from documents, chat apps or styled-font generators can fail in ways that look puzzling. The text looks right on screen, but the underlying characters differ from what the pattern expects.

  • ASCII-only classes: \w, [a-z] and \d without the u flag do not cover accented or non-Latin letters. A name such as 'José' fails /^\w+$/.
  • Combining marks: 'é' may be stored as one precomposed code point or as 'e' plus a combining accent. A pattern that allows letters but not marks accepts the first form and rejects the second. Using \p{L}\p{M} with the u flag accepts both. Normalizing input to NFC before validation also makes behavior consistent.
  • Styled Unicode 'fonts': mathematical bold or script letters are separate code points, not formatted ASCII. A pattern like [A-Za-z] rejects them. Whether to accept them is a product decision, but accepting them affects search, sorting and readability for assistive technology.
  • Invisible characters: zero-width spaces, non-breaking spaces and bidirectional control characters can arrive through copy and paste. Decide whether to strip them before validation or reject them explicitly.
  • Emoji: many emoji span several code points, joined by zero-width joiners or modifiers. Length quantifiers like {1,10} count UTF-16 code units, not visible characters, unless you account for this separately.
class ProfileDto {
  // Letters and combining marks from any script, plus space, apostrophe and hyphen
  @Matches(/^[\p{L}\p{M}' -]{1,50}$/u)
  displayName: string;
}

If a field will be displayed, searched or read aloud by screen readers, keeping it to ordinary characters is usually the practical choice. Validation can enforce that, but it cannot convert stylized input back to plain text. That conversion needs an explicit normalization or rejection step with a clear error message.

Matches compared with alternatives

Approach | Best for | Tradeoff
Matches | Formats with no built-in validator, such as codes, slugs and constrained identifiers | Pattern correctness, Unicode handling and performance are your responsibility
Built-in validators (IsEmail, IsUUID, IsAlphanumeric and similar) | Well-known formats | Less control over edge cases; behavior is defined by the library
Custom validator class or ValidateBy | Cross-field rules, checksums, lookups, logic beyond regex | More code to write and test
Transform, then validate | Input that needs trimming, case folding or normalization first | Requires a clear pipeline order

Gaps in this review

No version-specific documentation, changelogs, benchmarks or framework test results were supplied for this review. The behavior described here reflects the general design of class-validator and JavaScript regular expressions. Confirm the exact signature, default messages and edge-case behavior against the version installed in your project. Write unit tests for each pattern, including accented input, decomposed characters, emoji and pasted whitespace, rather than assuming one successful case covers them all.