Avoid Stateful RegExp.test with Global and Sticky Flags
A form accepts a value on the first check and rejects the identical value on the next check. The pattern looks correct, but a shared regular expression carries a matching cursor between calls.
For ordinary Boolean validation, leave the g and y flags off. Keep cursor-based expressions local to code that deliberately manages their position. These examples use built-in JavaScript regular expressions and run in modern browsers or Node.js 20 or later.
Reproduce the Alternating Result
Run this small example before changing a larger validator:
The anchors constrain the match to the input boundaries, but g still makes matching start from lastIndex. The first successful match leaves the cursor at 7. On the next call, the anchored pattern cannot match from there, and the failed search resets the cursor to zero.
The RegExp.test documentation describes how repeated tests on global expressions advance this shared cursor. A Boolean return value does not make the operation free of state.
This also affects array callbacks. Reusing one global expression inside filter() can accept or reject a row based on the row checked before it, including a row containing a different string.
Distinguish Validation from Cursor-Based Matching
For ordinary expressions using the built-in matching methods, the relevant rules are:
| Flags | Starting position | State after matching |
|---|---|---|
Neither g nor y | Search starts at zero | lastIndex is not updated |
g | Search starts at lastIndex, and may search later positions | Success stores match end; failure resets to zero |
y | Match must start exactly at lastIndex | Success stores match end; failure resets to zero |
Other flags have different purposes. For example, i enables case-insensitive matching without introducing a cursor. A pattern without anchors still tests whether a matching substring exists; removing g does not turn a substring search into whole-value validation.
These rules come from the
ECMAScript RegExpBuiltinExec algorithm
. They describe ordinary built-in behavior; custom exec() methods and subclasses can supply different behavior.
Keep the Validator Free of a Shared Cursor
Save this as item-code.mjs:
This contract accepts the lowercase prefix item- followed by one or more ASCII digits. It permits leading zeros and imposes no numeric range or length limit. It rejects whitespace, line terminators, and non-string inputs, without trimming or converting them.
The explicit line-terminator check makes the whole-value rule visible and keeps future pattern edits from accepting a separate trailing line. Keep the m flag off: multiline anchors would describe individual lines instead of this complete value. Neither expression in this helper has g or y, so repeated calls do not depend on a matching cursor.
Use the helper directly in a filter callback:
Avoid accepting arbitrary user-supplied regex patterns just to solve this problem. A small fixed validator is easier to review. This example checks syntax only; whether an item exists remains a separate lookup.
Give Sticky Matching Its Own Cursor
The y flag is useful when matching at an explicit position, such as reading a token from a known offset:
At offset 2 the input contains a space, so sticky matching fails immediately instead of skipping to BB. The owner of the parsing operation must choose the next position explicitly. Keep the expression inside that operation rather than sharing it with unrelated validation calls.
If a global or sticky expression must be reused for independent inputs, reset its cursor before every input. That still retains its matching semantics: resetting a sticky pattern to zero cannot make it search later positions. For a fixed Boolean validator, omitting cursor flags is simpler.
The
lastIndex reference
also illustrates zero-length matches. A successful empty match can leave the cursor unchanged, so a manual exec() loop needs an explicit progress policy. That is another reason to keep iteration separate from validation.
Test Repeated and Interleaved Inputs
Save this as test-item-code.mjs and run node test-item-code.mjs:
| |
A test with one valid value and one invalid value may miss the shared-cursor bug because the invalid check resets the cursor. Consecutive valid inputs, duplicate rows, and interleaved values expose that dependence. Keep those cases whenever a validator is reused across form events or collection operations.