Yup string().matches() rejects values that should pass
An optional phone or zip field shows the pattern error when left emptyShort answer
Three things break matches in practice. An optional field fails on an empty string unless you set excludeEmptyString. A required() check fires first on empty strings, so its message shows instead of the pattern message. And a regex with the g flag keeps state between calls and alternates results. Check these before changing the pattern.
Fix it fast
1Find out which cause you have
Test the schema outside React with the exact value that fails. If it fails there too, the schema is the problem, not the form library.
console.log(await schema.isValid('')); console.log(await schema.isValid('0300123456')); console.log(await schema.isValid('0300123456'));2Match what you see, then jump to its fix
- 1
Fails only when the field is empty or clearedAn optional field is empty and the regex does not allow emptyFix - 2
An empty value shows the required message, not the pattern messageA required field is empty but you expected a different messageFix - 3
The same valid value alternates between passing and failingThe regex has the g flag and keeps state between testsFix
- 1
What does the error look like?
An optional phone or zip field shows the pattern error when left emptyThe same valid value passes, then fails on the next validationAn empty field shows the required message instead of the pattern message
Cause 1 of 3
An optional field is empty and the regex does not allow empty
1Check
Most patterns need at least one character, so an empty string fails them. The field is optional, but matches still runs on ''.
grep -rn "matches(" src/2Fix
Pass excludeEmptyString: true. The regex test is skipped for empty strings, so the pattern stays unchanged.
const schema = yup.string().matches(/^[0-9]{10}$/, {
message: 'Enter 10 digits',
excludeEmptyString: true,
});3Verify
isValid('') is true, and isValid('123') is false.
console.log(await schema.isValid(''));
console.log(await schema.isValid('123'));Confirmed by raw.githubusercontent.com
Cause 2 of 3
A required field is empty but you expected a different message
1Check
For strings, required() treats an empty string as missing, so the required error comes first for an empty value.
grep -rn "required(" src/2Fix
Give required() its own message so the two errors read correctly, and keep the pattern message on matches. If the field is optional, drop required() and use excludeEmptyString instead.
yup.string()
.required('Phone is required')
.matches(/^[0-9]{10}$/, { message: 'Enter 10 digits' });3Verify
Submit empty, then a bad value; each shows its own text.
npm testConfirmed by raw.githubusercontent.com
Cause 3 of 3
The regex has the g flag and keeps state between tests
1Check
A regex with g or y keeps lastIndex between test() calls, and lastIndex does not reset while test() returns true, even for a different string. A shared regex literal reused by a schema is affected.
grep -rnE "matches\(/.*/[a-z]*g" src/2Fix
Remove the g flag from validation patterns; a validation test never needs it.
// before
yup.string().matches(/^[a-z]+$/g, { message: 'letters only' });
// after
yup.string().matches(/^[a-z]+$/, { message: 'letters only' });3Verify
Validate the same good value several times; it passes every time.
for (let i = 0; i < 3; i++) console.log(await schema.isValid('abc'));Confirmed by developer.mozilla.org
How do I stop it coming back?
- Unit-test each schema with empty, valid and invalid values.
- Never use the g flag in a regex used for validation.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
- TaskvareA task and project-management suite: React on the web, Flutter on mobile, TypeScript underneath.
Related fixes
Web apps
Module not found for antd/dist/antd.less after upgrading to Ant Design 5
Module not found: Error: Can't resolve 'antd/dist/antd.less'
Ant Design 5 dropped Less and the bundled CSS file for CSS-in-JS, so antd/dist/antd.less no longer exists.
3 causes, each with a fixWeb apps
Astro Code component fails inside a React component
Astro components cannot be rendered directly via function call
Astro components such as Code only exist on the server and render static HTML.
2 causes, each with a fixWeb apps
React shows Attempted import error when importing a component or function
Attempted import error:
The build found the file but not the name you asked for.
2 causes, each with a fixWeb apps
How to catch and handle a 422 from Axios in a Redux thunk
action.error.message is 'Rejected' and action.payload is undefined
A 422 means the server read the request but cannot process its content, so repeating it unchanged fails again.
4 causes, each with a fixWeb apps
axios gets 429 Too Many Requests from a React app
429 (Too Many Requests)
A 429 comes from the server or an API gateway, not from axios: your client sent too many requests in a window.
4 causes, each with a fixWeb apps
Axios request is not cancelled when a React component unmounts
A cancelled request is logged as an error in the catch block
Axios cancels a request when you pass it an AbortSignal and later call abort() on its controller.
4 causes, each with a fix