devcrea

HTML pattern Attribute Not Working? Fix v-Flag Regexes

Browsers compile HTML pattern regexes with the v flag and silently ignore syntax errors. Spot broken character classes, escape rules, and DOM checks.

// The short answer

Modern browsers compile HTML pattern attributes using the JavaScript v flag (unicodeSets) and silently drop the validation rule whenever the regex throws a syntax error. Unescaped hyphens, brackets, parentheses, slashes, pipes, or doubled punctuators inside [...] cause the browser to treat the field as always valid. Run new RegExp(input.pattern, 'v') in DevTools to expose the SyntaxError and backslash-escape the reserved characters.

Full walkthrough, edge cases and why it works
In this guide · 6 sections
  1. 01Why Invalid pattern Regexes Fail Silently in Browsers
  2. 02Reproduce and Diagnose the Failure in Browser DevTools
  3. 03Characters That Break Under the v Flag
  4. 04Broken vs. Fixed HTML pattern Examples
  5. 05Other Reasons Your pattern Attribute Stops Matching
  6. 06Compatibility and Verification Before Shipping

Modern browsers compile every HTML pattern attribute using the ECMAScript v flag (unicodeSets), and the HTML Standard tells browsers to ignore any syntax error in that regular expression instead of throwing one. Whenever a character class contains an unescaped hyphen or reserved punctuator that used to work under the older u flag, the browser quietly drops your validation rule and lets bad form data go right through. Running new RegExp(input.pattern, 'v') in your browser console immediately surfaces the syntax error so you can escape the offending character and get validation working again.

Check Value / Behavior
Compilation rule Anchored automatically as ^(?:<pattern>)$ with the v flag
On syntax error Constraint is quietly ignored, and input.validity.patternMismatch stays false
Fastest diagnostic new RegExp(document.querySelector('#your-input').pattern, 'v')
Most common break Unescaped -, /, (, ), [, ], {, }, `
Supported input types text, search, tel, url, email, password (ignored on number and <textarea>)

Why Invalid pattern Regexes Fail Silently in Browsers

Under the WHATWG HTML Standard, a browser grabs the raw string from your pattern attribute, wraps it in a non-capturing group anchored to both ends of the value (^(?:...)$), and compiles it with the JavaScript v flag. If that compilation fails, the spec tells the browser to treat your input as if it has no pattern rule at all.

You end up with a sneaky failure mode. Your form keeps working, no uncaught exception stops your JavaScript, and happy-path tests with valid input pass without a hitch. You only catch the bug when you submit an invalid value and watch the browser accept it without saying a word.

Older debugging advice, and plenty of online regex testers, make this easy to miss because they run expressions with default JavaScript flags or the u flag. A pattern like [a-z0-9-_]+ compiles cleanly under new RegExp('[a-z0-9-_]+', 'u'), yet blows up under the v flag with SyntaxError: Invalid character in character class. Because browsers moved HTML pattern compilation from u to v, legacy regexes copied from older docs or Stack Overflow threads now fail quietly in production.

Reproduce and Diagnose the Failure in Browser DevTools

Grab a modern browser (Chromium 114+, Firefox 116+, or Safari 17+) and open DevTools to see if the v flag is rejecting your pattern. Do not stop at testing in Node.js alone, because browser DevTools also let you inspect how the DOM ValidityState reacts on a real <input> element.

Step 1: Compile the Pattern with the v Flag

Inspect your target <input> element and run this snippet in the browser console:

js2 lines
const input = document.querySelector('#sku-code');
new RegExp(input.pattern, 'v');

Compare that result against the u flag on the exact same string:

js6 lines
// Passes under u, fails under v
new RegExp('[a-z0-9-_]+', 'u');
// -> /[a-z0-9-_]+/u

new RegExp('[a-z0-9-_]+', 'v');
// -> Uncaught SyntaxError: Invalid regular expression: /[a-z0-9-_]+/v: Invalid character in character class

If new RegExp(input.pattern, 'v') throws a SyntaxError, your browser is ignoring that pattern attribute completely.

Step 2: Check input.validity.patternMismatch and Console Warnings

To verify the live DOM behavior, assign a value that should fail validation and check validity.patternMismatch:

js8 lines
const input = document.querySelector('#sku-code');
input.value = 'INVALID VALUE!!!';

console.log({
  pattern: input.pattern,
  patternMismatch: input.validity.patternMismatch,
  valid: input.validity.valid
});

When the regex breaks under v, the console logs patternMismatch: false and valid: true even though your test string clearly violates the format you wanted. Chromium-based browsers also print a console error right when the page parses or validates the bad attribute:

Plaintext

code1 line
Pattern attribute value [a-z0-9-_]+ is not a valid regular expression: Uncaught SyntaxError: Invalid regular expression: /[a-z0-9-_]+/v: Invalid character in character class

Once you fix the escaping and run that same snippet again, patternMismatch flips to true and valid flips to false.

Characters That Break Under the v Flag

The v flag brings set notation, like union, intersection &&, and subtraction --, along with nested character classes inside [...]. To parse those rules without ambiguity, the engine rejects several literal characters inside a character class unless you escape them with a backslash (\).

Character(s) inside [...] Status under u flag Status under v flag Safe v-flag syntax
- (literal hyphen, not a range) Allowed in some positions (e.g. [a-z-_]) Throws SyntaxError unless at start/end or escaped [\-] (escape it everywhere to stay safe)
( and ) Allowed unescaped Reserved, throws SyntaxError \( and \)
[ and ] [ allowed unescaped Reserved for nested classes, throws SyntaxError [ and ]
{ and } Allowed unescaped Reserved, throws SyntaxError \{ and \}
/ Allowed unescaped Reserved, throws SyntaxError \/
` ` Allowed unescaped Reserved, throws SyntaxError
Double punctuators (--, &&, !!, ##, $$, %%, **, ++, ,, .., ::, ;;, <<, ==, >>, ??, @@, ^^, ````, ~~) Allowed unescaped Reserved for current or future set operators, throws SyntaxError Escape at least one (e.g. \-\-, \&\&, \.\.)

A literal hyphen sitting at the very start ([-a-z]) or very end ([a-z-]) of a character class still compiles under v, though escaping it as \- prevents position-dependent bugs if you tack another character onto the class later.

Broken vs. Fixed HTML pattern Examples

Every pair below was tested directly on an <input type="text"> element by feeding in a bad string ("bad input!") and reading input.validity.patternMismatch.

1. Unescaped Hyphen Inside a Character Class

html5 lines
<!-- Broken under v: hyphen sits between 0-9 and _ -->
<input id="slug" type="text" pattern="[a-z0-9-_]+">

<!-- Fixed: hyphen escaped -->
<input id="slug" type="text" pattern="[a-z0-9\-_]+">
  • Broken result: patternMismatch stays false for "bad input!".
  • Fixed result: patternMismatch turns true for "bad input!" and false for "my-slug_01".

2. Unescaped Parentheses or Slashes in a Phone or Date Mask

html5 lines
<!-- Broken under v: (, ), and / are unescaped inside [...] -->
<input id="phone" type="text" pattern="[0-9 ()+-/]{7,20}">

<!-- Fixed: reserved characters escaped -->
<input id="phone" type="text" pattern="[0-9 \(\)+\-\/]{7,20}">
  • Broken result: new RegExp(input.pattern, 'v') throws Invalid character in character class, and patternMismatch stays false.
  • Fixed result: patternMismatch turns true for "call me" and false for "+1 (555) 123-4567".

3. Unescaped Double Punctuators

html5 lines
<!-- Broken under v: && is parsed as set intersection -->
<input id="code" type="text" pattern="[A-Z0-9&&]+">

<!-- Fixed: escape the doubled ampersand -->
<input id="code" type="text" pattern="[A-Z0-9\&\&]+">
  • Broken result: SyntaxError: Invalid set operation in character class fires, and validation gets bypassed.
  • Fixed result: patternMismatch turns true for "abc" and false for "A&B".

Keep in mind that the standard WHATWG email regex is already v-safe once you escape its forward slash properly, so if you are debugging email or TLD validation rules specifically, check your HTML input type="email" TLD validation behavior instead of rewriting that standard expression.

Other Reasons Your pattern Attribute Stops Matching

If new RegExp(input.pattern, 'v') runs cleanly without throwing an error and your field still skips validation, one of four HTML rules usually explains why.

Unsupported Input Types (type="number", <textarea>)

The pattern attribute only works on text, search, tel, url, email, and password inputs. Putting pattern on <input type="number"> or <textarea> does nothing at all, and the browser ignores it without logging a single warning. For numeric codes with leading zeros or fixed formatting, like postal codes, SKUs, or OTPs, reach for <input type="text" inputmode="numeric" pattern="[0-9]{6}"> instead of type="number".

Wrapping the Pattern in JavaScript Slashes

Skip the leading and trailing / delimiters or flags inside your HTML attribute:

html5 lines
<!-- Wrong: browser looks for literal forward slashes in the user's input -->
<input type="text" pattern="/^[A-Z]{3}$/">

<!-- Right: raw expression only, since ^(?:...)$ anchoring is automatic -->
<input type="text" pattern="[A-Z]{3}">

Because the browser already wraps your pattern in ^(?:...)$, putting /.../ around it forces your users to type literal slashes at the start and end of the field.

Empty Values Without required (and pattern="")

An empty input never triggers patternMismatch. If the field is mandatory, pair pattern with required:

html1 line
<input type="text" pattern="[A-Z]{2}-[0-9]{4}" required>

Avoid leaving an empty pattern="" attribute in your markup too. An empty string compiles as ^(?:)$, which only matches an empty string and rejects any non-empty text someone types in.

Form-Level novalidate or formnovalidate

Inspect the parent <form> element for a novalidate attribute and your submit <button> for formnovalidate. Either attribute turns off native HTML constraint validation on submit, even when input.validity.patternMismatch accurately evaluates to true in JavaScript.

Compatibility and Verification Before Shipping

All major browser engines, Blink (Chrome/Edge 114+), Gecko (Firefox 116+), and WebKit (Safari 17+), now compile HTML pattern attributes with the v flag. Escaping -, (, ), [, ], {, }, /, |, and double punctuators inside [...] stays backward-compatible with older u-flag engines too, so a v-safe pattern works reliably across both current and legacy browsers.

Before you ship any form change:

  1. Run new RegExp(el.pattern, 'v') in the browser console on every input using pattern. 2. Test at least one invalid value per field and confirm that el.validity.patternMismatch returns true. 3. Mirror that exact same v-flag regex in your catastrophic backtracking in JavaScript regex on your server-side validator so your client and backend rules never drift apart.

Quick answers

Frequently asked questions

Why does an invalid HTML pattern attribute let users submit without showing an error?

Under the WHATWG HTML Standard, browsers ignore any pattern attribute whose regular expression fails to compile with the v flag. Instead of throwing an exception, the browser drops your validation constraint and keeps input.validity.patternMismatch set to false.

Why does my regex pass in online testers or new RegExp() but fail in an HTML input?

Most regex testers and standard JavaScript RegExp calls default to no flag or the u flag, whereas browsers compile your HTML pattern values with the v flag. That v flag enforces stricter syntax inside character classes, rejecting unescaped hyphens, brackets, parentheses, forward slashes, pipes, and doubled punctuators.

How can I check if the browser is ignoring my HTML pattern attribute?

Select the input element in DevTools and run new RegExp(input.pattern, 'v') in the console to see whether it throws a SyntaxError. You can also assign a known invalid string to input.value and verify that input.validity.patternMismatch returns true.

Which characters need a backslash escape inside brackets under the v flag?

Inside a character class, escape literal hyphens, parentheses, square brackets, curly braces, forward slashes, and vertical pipes with a backslash. You also need to escape at least one character in any doubled punctuator pair, such as --, &&, or .., so the engine does not parse it as a set operation.

Why does the pattern attribute not work on input type="number" or textarea?

HTML constraint validation applies the pattern attribute only to text, search, tel, url, email, and password inputs. Browsers ignore pattern completely on number inputs and textareas without logging a warning, so use input type="text" with inputmode="numeric" when you need formatted numeric codes.

Should I wrap an HTML pattern attribute value in forward slashes like /regex/?

No, write only the raw regular expression without leading or trailing slashes or flags. Because the browser automatically anchors your expression as ^(?:your-pattern)$, adding slashes forces your users to type literal slash characters at the start and end of their input.

Why does an empty input pass validation when a pattern attribute is set?

An empty value never triggers a patternMismatch on its own. Add the required attribute alongside pattern if users cannot leave the field blank, and avoid leaving an empty pattern="" attribute because it rejects any non-empty value.

Something wrong or out of date?

Tools change fast. Tell the editor what no longer works.