Regex Yup Validation: How string().matches() Works and When to Use It

A practical review of regex validation in Yup: what matches() checks, how it interacts with transforms, empty values and Unicode input, and when a simpler rule is the better choice.

Yup is a JavaScript schema library often used to validate form input. When a built-in rule like email() or url() does not fit, developers usually turn to string().matches(), which tests a string against a regular expression. This review covers what that method checks, what it leaves unchanged, and where regex-based validation helps or causes problems. It describes Yup's documented API and general JavaScript regex behavior. No version-specific tests were supplied for this article, so confirm details against the documentation for the Yup version you use.

Is regex validation in Yup the right fit?

Use matches() when the rule is about the shape of a string, such as an allowed character set, a fixed-format code or a username pattern. You can write the pattern once in the schema and reuse it on the client and the server. The main cost is readability. A long regex is hard to review and easy to get subtly wrong. Its failure tells you only that the input did not match, not which part was wrong.

A plainer approach is usually better in these cases:

  • A built-in rule already covers the need, such as email(), url(), uuid(), min(), max() or length().
  • The rule depends on meaning rather than shape, such as whether a date exists or a username is available. These need a custom test() or a server-side check.
  • The accepted format varies by region or language. Personal names and international phone numbers are common examples, and a strict pattern rejects valid input.
  • You need several specific error messages. Chained min(), max() and smaller patterns give clearer feedback than one combined expression.

What matches() actually changes

matches() is a test, not a transformation. It reads the value and reports pass or fail, and it never rewrites the characters. Yup does change values through other methods. trim(), lowercase(), uppercase() and custom transform() functions run during casting. By default validate() casts first and then runs the tests, so a pattern is checked against the transformed value. With strict mode enabled, transforms are skipped and the pattern sees the raw input.

A typical schema combines a transform, a presence check and a pattern:

import * as yup from 'yup';

const schema = yup.object({
  username: yup
    .string()
    .trim()
    .required('Enter a username')
    .matches(/^[a-z0-9_]{3,20}$/, 'Use 3–20 lowercase letters, digits or underscores'),
});

Here trim() removes surrounding whitespace before the test. matches() then only accepts or rejects what remains and does not convert uppercase input to lowercase. If you want uppercase input lowercased instead of rejected, add lowercase() as a separate step.

Anchors decide what counts as a match

A JavaScript regex test passes if the pattern is found anywhere in the string. Without ^ and $, a pattern like /[a-z0-9_]{3,20}/ accepts "ok_name!!!" because a valid substring exists. To validate the whole value, anchor the pattern at both ends.

Avoid the global flag

A regex with the g flag keeps a lastIndex position between calls to test(). If the same expression object is reused, as it is in a schema, identical input can pass and then fail on alternate runs. This is standard JavaScript behavior, and validation patterns rarely need g:

const re = /^\d+$/g;
re.test('123'); // true
re.test('123'); // false: lastIndex advanced past the first match

Empty and missing values

Presence and format are separate rules. Recent Yup versions skip matches() for absent values (undefined). Use required() when a field must be filled in, and nullable() when null is acceptable. An empty string is not absent, so an anchored pattern will usually reject it. For an optional field where blank is allowed, pass the excludeEmptyString option:

phone: yup.string().matches(/^\+?[0-9 ()-]{7,20}$/, {
  message: 'Enter a valid phone number',
  excludeEmptyString: true,
}),

The handling of absent values has changed across Yup releases. If your validation depends on this edge case, check it against your installed version.

Will it still work with pasted and international text?

Most surprises in regex validation come from text pasted into the field. Several Unicode details affect whether valid input passes:

  • Character classes like [a-zA-Z] cover only unaccented Latin letters. To accept letters in any script, use Unicode property escapes such as \p{L}. These require the u flag.
  • An accented letter can be stored as one code point or as a base letter plus a combining mark. Text that looks identical may then match one pattern and fail another. Normalizing to NFC in a transform before the test reduces this mismatch.
  • Emoji and some other characters span multiple code points. Length limits in a pattern, or min() and max(), count code units rather than visible characters, so the limits may not match what the user sees.
  • Pasted text can carry invisible characters such as non-breaking spaces or zero-width characters. trim() removes some whitespace but will not catch every invisible code point, so an anchored pattern may reject input that looks valid.
name: yup
  .string()
  .transform((value) => (typeof value === 'string' ? value.normalize('NFC') : value))
  .matches(/^[\p{L}\p{M}' -]+$/u, 'Use letters, spaces, apostrophes or hyphens'),

Normalization in a transform changes the value that gets submitted, not just the value that gets tested. If the original form must be stored exactly as entered, normalize a copy inside a custom test() instead.

Readable error messages

Users never see the regex, only the message. A message that names the accepted characters and length is more useful than "Invalid format" and easier to read aloud with assistive technology. Yup does not connect the message to the input field. Your form code has to expose the error and associate it with the field, for example through aria-describedby, so screen readers announce it. Behavior in specific screen readers or browsers has not been tested for this article.

Performance and trust limits

Patterns with nested quantifiers, such as (a+)+, can backtrack excessively on some inputs and slow or freeze validation. Keep patterns simple and bounded, especially if the same schema runs on a server. Client-side Yup validation also improves the user experience but does not protect the server. Any rule that matters for security or data integrity must be checked again on the server.

Bottom line

string().matches() is a sound choice for fixed, well-defined string formats when the pattern is anchored, has no g flag, and comes with a plain-language error message. Pair it with required() for presence and with transforms for cleanup, keeping in mind that transforms change the submitted value. Use a built-in rule, a custom test() or a server check when the format is loose, depends on locale or language, or depends on meaning rather than shape.