Validate Input with express-validator's matches()

How express-validator's matches() checks request fields against a regex, where it fits, and how Unicode styled text, combining marks and bidi characters affect it.

What matches() does in express-validator

matches() is a validator that express-validator takes from the validator.js library and exposes on its validation chains. It tests a request field, such as a body property, query parameter or header, against a regular expression and records whether the value passed or failed. It accepts either a RegExp object or a pattern string with an optional flags string as the second argument. Validator.js works on strings, so express-validator converts the field value to a string before the check runs.

The most important distinction is that matches() changes nothing. Validators only report a result. Sanitizers such as trim(), escape(), normalizeEmail() and customSanitizer() rewrite the value that later code reads from the request or from matchedData(). If you want input converted into an acceptable shape, matches() is the wrong tool. It only decides whether the input already has that shape.

const express = require('express');
const { body, validationResult, matchedData } = require('express-validator');

const app = express();
app.use(express.json());

app.post(
  '/signup',
  body('username')
    .trim()
    .matches(/^[a-z0-9_]{3,20}$/i)
    .withMessage('Use 3 to 20 letters, digits or underscores.'),
  (req, res) => {
    const result = validationResult(req);
    if (!result.isEmpty()) {
      return res.status(400).json({ errors: result.array() });
    }
    const { username } = matchedData(req);
    res.json({ username });
  }
);

Three details in this example matter. The ^ and $ anchors force the whole value to match. Without them, any value that contains a matching substring passes. The chain runs in order, so trim() removes surrounding whitespace before matches() sees the value. withMessage() replaces the generic "Invalid value" error with a description the person filling in the form can act on.

Is matches() suitable for your input?

matches() is a good fit for fields that follow a defined format, such as usernames, slugs, product or reference codes, and internal identifiers. Its main benefit is that one declarative line enforces that format at the server boundary. The tradeoff is that a regular expression describes character shapes, not meaning. A tight pattern rejects legitimate input. A loose pattern admits the input you meant to exclude. Personal names, addresses and international text are where this tradeoff hurts most.

  • Use matches() when the field has a format you control and can state in one sentence.
  • Prefer a purpose-built validator when one exists, such as isEmail(), isUUID(), isISO8601(), isInt() or isURL(). These encode edge cases a hand-written pattern tends to miss.
  • Prefer plain, unconstrained text when the field holds human-written content such as names, comments or bios. For those fields, a length limit plus correct output encoding usually serves better than a character whitelist.
  • Do not rely on matches() as protection against injection or cross-site scripting. Encode or parameterize at the point of use instead.

Pattern details that change the outcome

  • Anchor the pattern with ^ and $ unless a partial match is genuinely what you want.
  • String patterns need double escaping in JavaScript source. To get \d+ you write '\d+', so a RegExp literal is usually easier to read.
  • Pass flags through the second argument when you use a string pattern, for example matches('^[a-z]+$', 'i').
  • Unicode property escapes such as \p{L} only work when the u flag is set.
  • The pattern runs against untrusted input, so avoid nested or overlapping quantifiers that can backtrack catastrophically on crafted strings. Keep the pattern simple and bound the field length.

Unicode input: styled "fonts", combining marks, emoji and reversed text

This is where regex validation meets text transformation tools. So-called "font" generators do not apply a font. They swap ordinary letters for different code points, often from the Mathematical Alphanumeric Symbols block. Upside-down and mirror generators also swap in lookalike characters from other blocks. Reversal tools reorder the code points. CSS transforms and bidirectional display, by contrast, change only how text is drawn and never reach your server. The exception is invisible bidi control characters, which someone can insert into the text itself. A server-side regex sees only the stored code points, never the visual presentation.

Input kind | What reaches the server | /^[A-Za-z]+$/ | /^\p{L}+$/u
Plain ASCII letters | Ordinary Latin code points | Passes | Passes
Accented letter, precomposed (NFC) | One letter code point | Fails | Passes
Accented letter, decomposed (NFD) | Base letter plus a combining mark | Fails | Fails unless \p{M} is also allowed
Styled "bold" or "script" letters from text generators | Mathematical Alphanumeric Symbols, which are letters but not Latin-script | Fails | Passes
Upside-down or mirrored lookalikes | Substitutes from various blocks, some letters and some punctuation or symbols | Fails | Letter substitutes pass, symbol substitutes fail
Emoji, including joined sequences | Several code points, possibly with zero-width joiners and variation selectors | Fails | Fails
Bidi control characters | Invisible format characters such as U+202E | Fails | Fails

The table follows from how JavaScript regular expressions define these character classes. It is not the result of tests run for this article. Reversed text needs a separate note. A character-class pattern does not check order, so reversed text passes exactly when the original does. The class will not notice if reversal detached a combining mark from its base letter or broke an emoji sequence apart. Detecting that requires a different check.

Styled letters force a decision. A \p{L} pattern accepts them. That may be acceptable for a display name, but it is a problem for usernames, where lookalikes enable impersonation and defeat search. There are two common responses. You can restrict the script, for example with \p{Script=Latin}; mathematical alphanumerics belong to the Common script, so they are rejected. Or you can apply NFKC normalization in a customSanitizer, which converts styled letters to their plain equivalents. NFKC changes the stored characters, and it also folds other compatibility characters. Ligatures, fullwidth forms and superscripts are rewritten, so "x²" becomes "x2". Use it only where that loss of meaning is acceptable.

body('displayName')
  .trim()
  .customSanitizer(value =>
    typeof value === 'string' ? value.normalize('NFC') : value
  )
  .matches(/^[\p{L}\p{M}' -]{1,50}$/u)
  .withMessage('Use letters, spaces, apostrophes or hyphens, up to 50 characters.'),

body('bio')
  .optional()
  .isLength({ max: 500 })
  .not()
  .matches(/[\u202A-\u202E\u2066-\u2069]/)
  .withMessage('Remove text direction control characters.'),

In the first chain, NFC normalization makes precomposed and decomposed accents compare alike. The pattern still allows \p{M}, because some letter and mark combinations have no precomposed form. The {1,50} quantifier counts code points, not the characters a reader perceives, so a limit near the boundary can reject a name that looks short enough. The second chain leaves free text mostly unconstrained and uses not().matches() to reject only bidi embedding, override and isolate controls. A broader exclusion such as \p{Cf} would also reject the zero-width joiner that many emoji sequences depend on.

Will validated text stay readable and usable after copying or sharing?

matches() itself does not affect this, because it stores whatever passed unchanged. What matters is what your pattern lets through. If you accept styled Unicode letters, you store and later display those code points. Copying generally preserves them, but a destination font may lack the glyphs. Searches for plain letters will not find them unless you normalize. Screen readers may announce them differently from ordinary letters or skip them. That behavior varies by assistive technology and was not tested for this article. Where people need to find, sort or listen to the text, keep a plain-text or normalized copy alongside the styled one, or reject styled input.

Bidi control characters are the clearest case of display diverging from storage. They change the visual order of text without changing its stored order, so a value can read one way on screen while containing something else. Rejecting them is reasonable for single-line identifiers. Content that genuinely mixes right-to-left and left-to-right scripts may need them, so for those fields it is often better to isolate user text when rendering it than to reject it outright.

Error messages are part of usability too. Describe the allowed format in words through withMessage() rather than echoing the regex. If you mirror the rule in a client-side pattern attribute for earlier feedback, treat the server-side check as the authoritative one.

What this review could not verify

No subject-specific test results were available. The code and the table reflect the documented behavior of express-validator, validator.js and JavaScript regular expressions. They were not executed against a particular library version or Node.js release for this article. Rendering on specific platforms, copy and paste into specific applications, and screen reader announcements were not tested. The express-validator API has changed between major versions, so confirm chain behavior and helper names against the documentation for the version you install.

Bottom line

Use matches() for fields with a format you can state precisely, anchor the pattern, and pair it with sanitizers when you actually need the value changed. Use Unicode-aware patterns with deliberate choices about scripts, marks and normalization when international input is expected. For free-form human text, plain text with a length limit and safe output handling is usually the better choice than a restrictive pattern.