Commit 610dc86f31f for woocommerce
commit 610dc86f31fa9b9666d7aa8e8ac80fe53d0a678a
Author: Asuka <Kayano04@outlook.jp>
Date: Wed Nov 18 08:35:29 2026 +0900
Fix checkout fields whose pattern only PHP can compile (#70687)
* Fix checkout fields with a pattern only PHP can compile
The checkout block compiles a field's `pattern` with AJV as a JavaScript
`RegExp` with the `u` flag, but registration only checked it against PCRE.
PCRE accepts constructs `u` mode rejects, so a pattern such as
`^[0-9]{3}\-[0-9]{4}$` registered without complaint and then threw while the
form rendered. The exception reached the block's error boundary and unmounted
the whole section, every field with it.
Reject those patterns at registration. A new `JavaScriptPattern` class reports
the PCRE-only constructs `u` mode has no equivalent for, and `Validation`
reports the first one it finds at the point that already returns a schema
error, so the field is never registered and `_doing_it_wrong()` names it.
The check is a deny-list that only reports constructs it is certain about,
so a valid pattern is never turned away.
Keep the form usable for patterns that get through anyway, which covers sites
that registered one before this fix. `compileSchema` wraps `parser.compile()`
and returns null instead of throwing, so the affected field falls back to
server-side validation alone rather than taking the section down. Both
`useFormValidation` and `useFormFields` use it.
Document the two-engine split, the constructs to avoid, and the `\d`/`\w`/`\b`
Unicode difference between the engines.
Co-authored-by: CommandCodeBot <noreply@commandcode.ai>
* Address review on the checkout field pattern fix
Scope the fallback to the field that needs it. Compiling the whole form's
schema together meant one field with a pattern the browser rejects returned
null from `compileSchema` and turned off browser validation for every field in
that form. `hasUncompilablePattern` now lets the caller drop just that field
before compiling, so the rest stay in browser validation and only the offending
one falls back to server-side validation.
Note on the `$data` half of the same review finding: a pattern supplied through
a `$data` reference does not throw at validation time. AJV emits the runtime
`RegExp` construction inside a try/catch for `$data` patterns (see
`vocabularies/validation/pattern.js`), so a value it cannot compile fails
validation rather than raising. No change is needed for it, and a test pins the
pointer-is-not-a-pattern case.
Also from the review: cover the scanner branches that no data row reached, add
the `void` return type the unit-test conventions ask for, drop the unused
`$length` in `check_escape_tail`, and replace the short `preg_match()` prefix
checks with plain string functions.
The detector still reports 74 of the 78 corpus patterns PCRE accepts but
JavaScript rejects, with no false positives.
Co-authored-by: CommandCodeBot <noreply@commandcode.ai>
* Fix checkout schema traversal after review
* Reject additional incompatible checkout patterns
* Reject unsupported regex escapes and groups
* Restore registration of checkout fields with PHP-only patterns
* Fix blank pattern notice and limit console logging to admins
---------
Co-authored-by: CommandCodeBot <noreply@commandcode.ai>
Co-authored-by: Mike Jolley <mike.jolley@me.com>
diff --git a/docs/block-development/extensible-blocks/cart-and-checkout-blocks/additional-checkout-fields.md b/docs/block-development/extensible-blocks/cart-and-checkout-blocks/additional-checkout-fields.md
index 3eec33cbe14..d39aa8496b3 100644
--- a/docs/block-development/extensible-blocks/cart-and-checkout-blocks/additional-checkout-fields.md
+++ b/docs/block-development/extensible-blocks/cart-and-checkout-blocks/additional-checkout-fields.md
@@ -626,7 +626,7 @@ If these fields were rendered in the "contact" location instead, the code would
The `required`, `hidden`, and `validation` properties accept an `array` of [JSON Schema](https://json-schema.org/understanding-json-schema/about) to create conditional logic for fields. This allows you to dynamically control field visibility, requirement status, and validation rules based on the values of other fields.
-Schema is evaluated in the frontend in real-time, and on the backend at any update. This ensures fast and responsive UI, and consistent results between the client and server.
+Schema is evaluated in the frontend in real-time, and on the backend at any update. This ensures fast and responsive UI, and consistent results between the client and server. The two run different engines, so see [the `pattern` keyword](#the-pattern-keyword) for the one place where they can disagree.
### JSON Schema Structure
@@ -1034,6 +1034,39 @@ Validation can also be against other fields, for example, an alternative email f
In the example above, we used [format keyword](https://github.com/ajv-validator/ajv-formats) and `$data` to refer to the current field value via [JSON pointers](https://ajv.js.org/guide/combining-schemas.html#data-reference). We also used the `errorMessage` property to provide a custom error message.
+##### The `pattern` keyword
+
+`pattern` is compiled in the browser as a JavaScript `RegExp` with the `u` flag, and on the server as a PCRE pattern with the `u` modifier. Use a pattern that both engines accept so the rule can run in both places.
+
+Write patterns in [ECMA-262](https://tc39.es/ecma262/#sec-patterns) syntax. Draft-07 also recommends limiting yourself to a small set of tokens ([§6.3.3](https://json-schema.org/draft-07/draft-handrews-json-schema-validation-01#name-regular-expressions)), which is a good rule of thumb because those behave the same in both engines.
+
+PCRE accepts constructs JavaScript rejects in `u` mode. WooCommerce reports known incompatibilities through `_doing_it_wrong()` during registration for `required`, `hidden` and `validation` rules, including `patternProperties` keys. The field remains registered with its original rules so the server can continue applying them. If the browser cannot compile a rule, it skips that rule for the affected field while valid fields keep their browser validation.
+
+Avoid these constructs:
+
+| Construct | Example |
+| --- | --- |
+| Escaping a literal that is not syntax | `^[0-9]{3}\-[0-9]{4}$` (the `\-` throws outside a character class) |
+| Inline flags | `(?i)^abc$` |
+| PCRE anchors | `\Aabc\z` |
+| Possessive quantifiers | `^a++$` |
+| POSIX character classes | `^[[:alpha:]]+$` |
+| PCRE-only escapes | `\h`, `\R`, `\X`, `\K`, `\N` |
+| Atomic, comment, or PCRE named groups | `(?>a)`, `(?#comment)`, `(?P<name>a)` |
+
+The fix is usually to drop the backslash or rewrite the construct with the syntax both engines share. For example, use `^[0-9]{3}-[0-9]{4}$` instead of `^[0-9]{3}\-[0-9]{4}$`, and `^[0-9]+$` or `^\p{Nd}+$` instead of `^[[:digit:]]+$`.
+
+Even patterns both engines accept can produce different results, because the `u` modifier makes `\d`, `\w` and `\b` match Unicode on the server while JavaScript keeps them ASCII-only:
+
+| Pattern | Input | Browser | Server |
+| --- | --- | --- | --- |
+| `^\w+$` | `José` | no match | match |
+| `^\d+$` | `١٢٣` | no match | match |
+| `^\D+$` | `١٢٣` | match | no match |
+| `^\W+$` | `é` | match | no match |
+
+Where that matters, spell the class out. `[0-9]` is ASCII-only in both engines, and `\p{L}` is Unicode-aware in both once the `u` flag is set.
+
##### Date field validation
A field registered with `'type' => 'date'` holds a string. Its validation schema uses `'type' => 'string'` and `'format' => 'date'` to check for a real calendar date in `YYYY-MM-DD` format.
diff --git a/plugins/woocommerce/changelog/70214-checkout-field-pattern-javascript b/plugins/woocommerce/changelog/70214-checkout-field-pattern-javascript
new file mode 100644
index 00000000000..c30df333ffb
--- /dev/null
+++ b/plugins/woocommerce/changelog/70214-checkout-field-pattern-javascript
@@ -0,0 +1,4 @@
+Significance: patch
+Type: fix
+
+Stop an additional checkout field's pattern, when only PHP can compile it, from removing the whole checkout section.
diff --git a/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/form/compile-schema.ts b/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/form/compile-schema.ts
new file mode 100644
index 00000000000..cf3f8f03361
--- /dev/null
+++ b/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/form/compile-schema.ts
@@ -0,0 +1,146 @@
+/**
+ * External dependencies
+ */
+import { __ } from '@wordpress/i18n';
+import { CURRENT_USER_IS_ADMIN } from '@woocommerce/settings';
+import type Ajv from 'ajv';
+import type { ErrorObject } from 'ajv';
+
+/**
+ * Patterns already reported, so a re-render does not repeat the message.
+ */
+const reportedPatterns = new Set< string >();
+
+/**
+ * Collect the patterns in a schema, so a compile failure can name them.
+ *
+ * @param schema The schema to walk.
+ * @return The patterns found.
+ */
+const collectPatterns = ( schema: unknown ): string[] => {
+ if ( ! schema || typeof schema !== 'object' || Array.isArray( schema ) ) {
+ return [];
+ }
+
+ return Object.entries( schema as Record< string, unknown > ).flatMap(
+ ( [ key, value ] ) => {
+ if ( key === 'pattern' ) {
+ return typeof value === 'string' ? [ value ] : [];
+ }
+
+ if ( ! value || typeof value !== 'object' ) {
+ return [];
+ }
+
+ // Only schema keywords contain rules; const, enum and annotations hold data.
+ switch ( key ) {
+ case 'patternProperties':
+ return [
+ ...Object.keys( value ),
+ ...Object.values( value ).flatMap( collectPatterns ),
+ ];
+ case 'properties':
+ case 'definitions':
+ case '$defs':
+ case 'dependencies':
+ case 'allOf':
+ case 'anyOf':
+ case 'oneOf':
+ return Object.values( value ).flatMap( collectPatterns );
+ case 'items':
+ return Array.isArray( value )
+ ? value.flatMap( collectPatterns )
+ : collectPatterns( value );
+ case 'additionalItems':
+ case 'additionalProperties':
+ case 'contains':
+ case 'propertyNames':
+ case 'not':
+ case 'if':
+ case 'then':
+ case 'else':
+ return collectPatterns( value );
+ default:
+ return [];
+ }
+ }
+ );
+};
+
+/**
+ * A compiled schema validator.
+ *
+ * AJV attaches the errors of the last run to the validator itself, which is how
+ * the caller reads them.
+ */
+export type CompiledSchema = ( ( data: unknown ) => boolean ) & {
+ errors?: ErrorObject[] | null;
+};
+
+/**
+ * Whether the browser can compile every pattern in a schema.
+ *
+ * `pattern` values and `patternProperties` keys are compiled with the `u` flag,
+ * so this is the same check AJV makes, without needing a parser to hand.
+ *
+ * @param schema The schema to check.
+ * @return True when at least one pattern is one the browser rejects.
+ */
+export const hasUncompilablePattern = ( schema: unknown ): boolean =>
+ collectPatterns( schema ).some( ( pattern ) => {
+ try {
+ new RegExp( pattern, 'u' );
+ return false;
+ } catch {
+ return true;
+ }
+ } );
+
+/**
+ * Compile a schema without letting a pattern the browser rejects take the form down.
+ *
+ * AJV compiles `pattern` as a JavaScript `RegExp` with the `u` flag, so a
+ * pattern only PHP accepts throws here. The exception would reach the block's
+ * error boundary and unmount the whole section, every field with it. Skipping
+ * schema validation keeps the form usable; the server still enforces the rule.
+ *
+ * @param parser The schema parser.
+ * @param schema The schema to compile.
+ * @return The compiled validator, or null when the schema does not compile.
+ */
+export const compileSchema = (
+ parser: Ajv,
+ schema: Record< string, unknown >
+): CompiledSchema | null => {
+ try {
+ // AJV's own type says the validator may return a Promise when the schema
+ // is async. None of the schemas here are, so the boolean is unwrapped.
+ return parser.compile( schema as never ) as unknown as CompiledSchema;
+ } catch ( error ) {
+ if ( ! CURRENT_USER_IS_ADMIN ) {
+ return null;
+ }
+
+ const unseen = collectPatterns( schema ).filter(
+ ( pattern ) => ! reportedPatterns.has( pattern )
+ );
+
+ if ( unseen.length > 0 ) {
+ unseen.forEach( ( pattern ) => reportedPatterns.add( pattern ) );
+
+ // eslint-disable-next-line no-console
+ console.error(
+ __(
+ 'The checkout form skipped validation for a field whose pattern is not a valid JavaScript regular expression. Patterns are compiled in the browser with the `u` flag, so they must be valid ECMA-262. Offending pattern(s):',
+ 'woocommerce'
+ ),
+ unseen
+ );
+
+ // eslint-disable-next-line no-console
+ console.error( error );
+ }
+
+ return null;
+ }
+};
diff --git a/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/form/test/compile-schema.test.ts b/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/form/test/compile-schema.test.ts
new file mode 100644
index 00000000000..96cb1f824a6
--- /dev/null
+++ b/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/form/test/compile-schema.test.ts
@@ -0,0 +1,272 @@
+/**
+ * External dependencies
+ */
+import { renderHook } from '@testing-library/react';
+import { useSchemaParser } from '@woocommerce/base-hooks';
+import type { KeyedFormFields } from '@woocommerce/settings';
+import Ajv from 'ajv';
+
+/**
+ * Internal dependencies
+ */
+import { compileSchema, hasUncompilablePattern } from '../compile-schema';
+import { useFormValidation } from '../use-form-validation';
+
+jest.mock( '@woocommerce/base-hooks', () => ( {
+ useSchemaParser: jest.fn(),
+ usePrevious: jest.fn(),
+} ) );
+
+let mockIsAdmin = true;
+
+jest.mock( '@woocommerce/settings', () => ( {
+ ...jest.requireActual( '@woocommerce/settings' ),
+ get CURRENT_USER_IS_ADMIN() {
+ return mockIsAdmin;
+ },
+} ) );
+
+const createParser = () =>
+ new Ajv( {
+ allErrors: true,
+ $data: true,
+ strictSchema: false,
+ strict: false,
+ messages: true,
+ } );
+
+const schemaWithPattern = ( pattern: string ) => ( {
+ type: 'object',
+ properties: {
+ checkout: {
+ type: 'object',
+ properties: {
+ additional_fields: {
+ type: 'object',
+ properties: {
+ 'member/number': { type: 'string', pattern },
+ },
+ },
+ },
+ },
+ },
+} );
+
+describe( 'compileSchema', () => {
+ let consoleError: jest.SpyInstance;
+
+ beforeEach( () => {
+ mockIsAdmin = true;
+ consoleError = jest
+ .spyOn( console, 'error' )
+ .mockImplementation( () => {} );
+ } );
+
+ afterEach( () => {
+ consoleError.mockRestore();
+ } );
+
+ it( 'compiles a schema whose patterns the browser accepts', () => {
+ const validate = compileSchema(
+ createParser(),
+ schemaWithPattern( '^[0-9]{3}-[0-9]{4}$' )
+ );
+
+ expect( validate ).not.toBeNull();
+ expect(
+ validate?.( {
+ checkout: {
+ additional_fields: { 'member/number': '123-4567' },
+ },
+ } )
+ ).toBe( true );
+ expect( consoleError ).not.toHaveBeenCalled();
+ } );
+
+ it( 'returns null instead of throwing for a PCRE-only pattern', () => {
+ // What the browser rejects: an escaped hyphen outside a character class.
+ const validate = compileSchema(
+ createParser(),
+ schemaWithPattern( '^[0-9]{3}\\-[0-9]{4}$' )
+ );
+
+ expect( validate ).toBeNull();
+ } );
+
+ it( 'logs the offending pattern once, however often the schema is compiled', () => {
+ const parser = createParser();
+ const pattern = '^[0-9]{2}\\-[0-9]{2}$';
+ const schema = schemaWithPattern( pattern );
+
+ compileSchema( parser, schema );
+ compileSchema( parser, schema );
+ compileSchema( parser, schema );
+
+ expect( consoleError ).toHaveBeenCalledTimes( 2 );
+
+ const [ message, patterns ] = consoleError.mock.calls[ 0 ];
+ expect( message ).toContain( 'ECMA-262' );
+ expect( patterns ).toEqual( [ pattern ] );
+ } );
+
+ it( 'does not log a skipped pattern for shoppers', () => {
+ mockIsAdmin = false;
+
+ const validate = compileSchema(
+ createParser(),
+ schemaWithPattern( '^[0-9]{4}\\-$' )
+ );
+
+ expect( validate ).toBeNull();
+ expect( consoleError ).not.toHaveBeenCalled();
+ } );
+
+ it.each( [
+ { pattern: '^[a-z]+\\-$' },
+ { patternProperties: { '^[a-z]+\\-$': { type: 'string' } } },
+ ] )( 'keeps sibling fields in form validation with %j', ( validation ) => {
+ // Field.validation is typed as a document schema even for scalar field rules.
+ const fields = [
+ {
+ key: 'ns/bad',
+ label: 'Bad field',
+ required: true,
+ validation,
+ },
+ {
+ key: 'ns/good',
+ label: 'Good field',
+ required: true,
+ validation: { pattern: '^[0-9]{5}$' },
+ },
+ {
+ key: 'ns/matching',
+ label: 'Matching field',
+ required: true,
+ validation: { const: { $data: '1/ns~1good' } },
+ },
+ ].map( ( field, index ) => ( {
+ ...field,
+ optionalLabel: field.label,
+ autocomplete: 'off',
+ hidden: false,
+ index,
+ } ) ) as unknown as KeyedFormFields;
+ jest.mocked( useSchemaParser ).mockReturnValue( {
+ parser: createParser(),
+ data: {
+ cart: {},
+ customer: {},
+ checkout: {
+ create_account: false,
+ customer_note: '',
+ payment_method: 'cod',
+ additional_fields: {
+ 'ns/bad': 'anything',
+ 'ns/good': 'invalid',
+ 'ns/matching': 'different',
+ },
+ },
+ },
+ } );
+
+ const { result } = renderHook( () =>
+ useFormValidation( fields, 'order' )
+ );
+
+ expect( result.current.errors ).toEqual( {
+ 'ns/good': 'good field must match the pattern ^[0-9]{5}$',
+ 'ns/matching': 'matching field is invalid',
+ } );
+ } );
+} );
+
+describe( 'hasUncompilablePattern', () => {
+ it( 'is false for a schema whose patterns the browser accepts', () => {
+ expect(
+ hasUncompilablePattern( schemaWithPattern( '^[0-9]{3}-[0-9]{4}$' ) )
+ ).toBe( false );
+ } );
+
+ it( 'is true for a schema with a PCRE-only pattern', () => {
+ expect(
+ hasUncompilablePattern(
+ schemaWithPattern( '^[0-9]{3}\\-[0-9]{4}$' )
+ )
+ ).toBe( true );
+ } );
+
+ it( 'does not read a $data pointer as a pattern', () => {
+ // `pattern: { $data: '1/member/number' }` holds a pointer, not a pattern.
+ // The value it resolves to is checked by AJV at validation time.
+ const schema = {
+ type: 'object',
+ properties: {
+ 'member/number': {
+ type: 'string',
+ pattern: { $data: '1/other' },
+ },
+ },
+ };
+
+ expect( hasUncompilablePattern( schema ) ).toBe( false );
+ const validate = compileSchema( createParser(), schema );
+ expect(
+ validate?.( { 'member/number': '123-4567', other: '\\-' } )
+ ).toBe( false );
+ } );
+
+ it( 'detects patterns in patternProperties keys and subschemas', () => {
+ const schema = {
+ type: 'object',
+ patternProperties: {
+ '^[a-z]+\\-$': { type: 'string' },
+ },
+ };
+
+ expect( hasUncompilablePattern( schema ) ).toBe( true );
+ expect(
+ hasUncompilablePattern( {
+ patternProperties: {
+ '^[a-z]+-$': { pattern: '\\@' },
+ },
+ } )
+ ).toBe( true );
+ } );
+
+ it( 'does not read instance data as schemas', () => {
+ const value = { pattern: '\\@', patternProperties: { '\\-': {} } };
+ const schema = {
+ type: 'object',
+ properties: { pattern: { const: '\\@' } },
+ const: value,
+ enum: [ value ],
+ default: value,
+ examples: [ value ],
+ };
+
+ expect( hasUncompilablePattern( schema ) ).toBe( false );
+ const validate = compileSchema( createParser(), schema );
+ expect( validate?.( value ) ).toBe( true );
+ expect( validate?.( { pattern: 'different' } ) ).toBe( false );
+ } );
+
+ it( 'finds patterns in nested schemas and tuple items', () => {
+ expect(
+ hasUncompilablePattern( {
+ anyOf: [
+ { not: { properties: { pattern: { pattern: '\\@' } } } },
+ ],
+ } )
+ ).toBe( true );
+ expect(
+ hasUncompilablePattern( { items: [ { pattern: '\\@' } ] } )
+ ).toBe( true );
+ expect( hasUncompilablePattern( { items: { pattern: '\\@' } } ) ).toBe(
+ true
+ );
+ expect(
+ hasUncompilablePattern( { properties: { pattern: false } } )
+ ).toBe( false );
+ } );
+} );
diff --git a/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/form/use-form-fields.ts b/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/form/use-form-fields.ts
index 4a0cbbf9301..5bd4f84d9db 100644
--- a/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/form/use-form-fields.ts
+++ b/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/form/use-form-fields.ts
@@ -15,6 +15,7 @@ import fastDeepEqual from 'fast-deep-equal/es6';
* Internal dependencies
*/
import prepareFormFields from './prepare-form-fields';
+import { compileSchema } from './compile-schema';
import { hasSchemaRules } from './utils';
/**
@@ -61,13 +62,16 @@ export const useFormFields = < T extends keyof FormFields >(
schema = defaultConfig.required;
}
- try {
- const result = parser.validate( schema, data );
- field.required = result;
- } catch ( error ) {
- if ( CURRENT_USER_IS_ADMIN ) {
- // eslint-disable-next-line no-console
- console.error( error );
+ const validate = compileSchema( parser, schema );
+
+ if ( validate ) {
+ try {
+ field.required = validate( data );
+ } catch ( error ) {
+ if ( CURRENT_USER_IS_ADMIN ) {
+ // eslint-disable-next-line no-console
+ console.error( error );
+ }
}
}
}
@@ -89,13 +93,16 @@ export const useFormFields = < T extends keyof FormFields >(
schema = defaultConfig.hidden;
}
- try {
- const result = parser.validate( schema, data );
- field.hidden = result;
- } catch ( error ) {
- if ( CURRENT_USER_IS_ADMIN ) {
- // eslint-disable-next-line no-console
- console.error( error );
+ const validate = compileSchema( parser, schema );
+
+ if ( validate ) {
+ try {
+ field.hidden = validate( data );
+ } catch ( error ) {
+ if ( CURRENT_USER_IS_ADMIN ) {
+ // eslint-disable-next-line no-console
+ console.error( error );
+ }
}
}
}
diff --git a/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/form/use-form-validation.ts b/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/form/use-form-validation.ts
index 1b6902f2c58..af140d61119 100644
--- a/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/form/use-form-validation.ts
+++ b/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/form/use-form-validation.ts
@@ -25,6 +25,7 @@ import fastDeepEqual from 'fast-deep-equal/es6';
/**
* Internal dependencies
*/
+import { compileSchema, hasUncompilablePattern } from './compile-schema';
import { hasSchemaRules } from './utils';
type FormErrors = Partial< {
@@ -89,6 +90,7 @@ const getErrorsMap = (
};
const EMPTY_OBJECT: FormErrors = {};
+
/**
* Combines address fields, including fields from the locale, and sorts them by index.
*/
@@ -156,9 +158,23 @@ export const useFormValidation = (
return acc;
}, {} );
+ // A field whose pattern the browser rejects is left out rather than allowed
+ // to fail the compile, which would turn off browser validation for every
+ // other field in the form. Dropping just that field keeps the rest in
+ // browser validation and leaves the one field to server-side validation.
+ const compilableSchema = Object.entries( partialSchema ).reduce<
+ typeof partialSchema
+ >( ( acc, [ fieldKey, fieldSchema ] ) => {
+ if ( ! hasUncompilablePattern( fieldSchema ) && fieldSchema ) {
+ acc[ fieldKey as keyof FormFields ] = fieldSchema;
+ }
+
+ return acc;
+ }, {} );
+
let schemaErrorsMap = EMPTY_OBJECT;
- if ( Object.keys( partialSchema ).length > 0 && parser ) {
+ if ( Object.keys( compilableSchema ).length > 0 && parser ) {
const schema = {
type: 'object',
properties: {},
@@ -171,7 +187,7 @@ export const useFormValidation = (
properties: {
shipping_address: {
type: 'object',
- properties: partialSchema,
+ properties: compilableSchema,
},
},
},
@@ -184,7 +200,7 @@ export const useFormValidation = (
properties: {
billing_address: {
type: 'object',
- properties: partialSchema,
+ properties: compilableSchema,
},
},
},
@@ -197,18 +213,18 @@ export const useFormValidation = (
properties: {
additional_fields: {
type: 'object',
- properties: partialSchema,
+ properties: compilableSchema,
},
},
},
};
break;
}
- const validate = parser.compile( schema );
+ const validate = compileSchema( parser, schema );
// AJV mutates validate function and errors to it, so we reach from it. Result only has a boolean value if errors are present.
- const result = validate( data );
+ const result = validate ? validate( data ) : true;
- if ( ! result && validate.errors ) {
+ if ( ! result && validate?.errors ) {
schemaErrorsMap = getErrorsMap( validate.errors, formFields );
} else {
schemaErrorsMap = EMPTY_OBJECT;
diff --git a/plugins/woocommerce/client/blocks/changelog/70214-checkout-field-pattern-javascript b/plugins/woocommerce/client/blocks/changelog/70214-checkout-field-pattern-javascript
new file mode 100644
index 00000000000..4bc2ea37dd1
--- /dev/null
+++ b/plugins/woocommerce/client/blocks/changelog/70214-checkout-field-pattern-javascript
@@ -0,0 +1,4 @@
+Significance: patch
+Type: fix
+
+Keep a checkout section usable when an additional checkout field's pattern is not a valid JavaScript regular expression.
diff --git a/plugins/woocommerce/src/Blocks/Domain/Services/CheckoutFieldTypes/AbstractFieldType.php b/plugins/woocommerce/src/Blocks/Domain/Services/CheckoutFieldTypes/AbstractFieldType.php
index b9efec9995f..0c1ed78d7fc 100644
--- a/plugins/woocommerce/src/Blocks/Domain/Services/CheckoutFieldTypes/AbstractFieldType.php
+++ b/plugins/woocommerce/src/Blocks/Domain/Services/CheckoutFieldTypes/AbstractFieldType.php
@@ -66,6 +66,19 @@ abstract class AbstractFieldType {
if ( is_wp_error( $valid ) ) {
return $this->registration_error( $id, $rule_field . ': ' . $valid->get_error_message(), '8.6.0' );
}
+
+ $unsupported_pattern = Validation::find_unsupported_pattern( $options[ $rule_field ] );
+ if ( null !== $unsupported_pattern ) {
+ $this->doing_it_wrong(
+ sprintf(
+ 'Field with id: "%s" has a %s rule that is not compatible with JavaScript. %s The field will still be registered and the rule evaluated on the server.',
+ $id,
+ $rule_field,
+ $unsupported_pattern->get_error_message()
+ ),
+ '11.4.0'
+ );
+ }
}
return true;
diff --git a/plugins/woocommerce/src/Blocks/Domain/Services/CheckoutFieldsSchema/Validation.php b/plugins/woocommerce/src/Blocks/Domain/Services/CheckoutFieldsSchema/Validation.php
index 46c1f418570..0fe9da2f767 100644
--- a/plugins/woocommerce/src/Blocks/Domain/Services/CheckoutFieldsSchema/Validation.php
+++ b/plugins/woocommerce/src/Blocks/Domain/Services/CheckoutFieldsSchema/Validation.php
@@ -5,6 +5,7 @@ namespace Automattic\WooCommerce\Blocks\Domain\Services\CheckoutFieldsSchema;
use Automattic\WooCommerce\Blocks\Domain\Services\CheckoutFieldsSchema\DocumentObject;
use Automattic\WooCommerce\Internal\Checkout\DateFormatLimitParser;
+use Automattic\WooCommerce\Internal\Checkout\JavaScriptPattern;
use Opis\JsonSchema\Errors\ErrorFormatter;
use Opis\JsonSchema\Errors\ValidationError;
use Opis\JsonSchema\Parsers\DefaultVocabulary;
@@ -222,6 +223,87 @@ class Validation {
return true;
}
+ /**
+ * Reports the first `pattern` value or `patternProperties` key the browser cannot compile.
+ *
+ * This check is separate from meta-schema validation so PHP-valid rules can
+ * remain registered and enforced on the server.
+ *
+ * @internal For exclusive usage of WooCommerce core, backwards compatibility not guaranteed.
+ *
+ * @since 11.4.0
+ *
+ * @param mixed $rules The rules to walk.
+ * @param string $path The path to the rules, for the error message.
+ * @return WP_Error|null An error describing the pattern, or null when every pattern is usable.
+ */
+ public static function find_unsupported_pattern( $rules, string $path = '' ) {
+ if ( ! is_array( $rules ) ) {
+ return null;
+ }
+
+ if ( '' === $path && self::schema_is_unwrapped( $rules ) ) {
+ $rules = [
+ 'type' => 'object',
+ 'properties' => $rules,
+ ];
+ }
+
+ foreach ( $rules as $keyword => $value ) {
+ $child_path = $path . '/' . $keyword;
+ $patterns = [];
+
+ if ( 'pattern' === $keyword && is_string( $value ) ) {
+ $patterns[] = $value;
+ } elseif ( 'patternProperties' === $keyword && is_array( $value ) ) {
+ $patterns = array_map( 'strval', array_keys( $value ) );
+ }
+
+ foreach ( $patterns as $pattern ) {
+ $unsupported = JavaScriptPattern::find_unsupported_construct( $pattern );
+
+ if ( null !== $unsupported ) {
+ return new WP_Error(
+ 'woocommerce_rest_checkout_invalid_field_schema',
+ sprintf(
+ 'At "%s": The pattern "%s" is not a valid JavaScript regular expression, %s. Patterns are compiled in the browser with the JavaScript `u` flag, so they must be valid ECMA-262.',
+ rawurldecode( $child_path ),
+ $pattern,
+ $unsupported
+ )
+ );
+ }
+ }
+
+ if ( ! is_array( $value ) ) {
+ continue;
+ }
+
+ // Only schema keywords contain rules; const, enum and annotations hold data.
+ $subschemas = [];
+ if (
+ in_array( $keyword, [ 'properties', 'patternProperties', 'definitions', '$defs', 'dependencies', 'allOf', 'anyOf', 'oneOf' ], true ) ||
+ ( 'items' === $keyword && isset( $value[0] ) )
+ ) {
+ foreach ( $value as $key => $subschema ) {
+ $subschemas[ $child_path . '/' . $key ] = $subschema;
+ }
+ } elseif ( in_array( $keyword, [ 'items', 'additionalItems', 'additionalProperties', 'contains', 'propertyNames', 'not', 'if', 'then', 'else' ], true ) ) {
+ $subschemas[ $child_path ] = $value;
+ }
+
+ foreach ( $subschemas as $subschema_path => $subschema ) {
+ $nested = self::find_unsupported_pattern( $subschema, $subschema_path );
+
+ if ( null !== $nested ) {
+ return $nested;
+ }
+ }
+ }
+
+ return null;
+ }
+
/**
* Describes schema errors at the failing keyword instead of the outer schema wrapper.
*
diff --git a/plugins/woocommerce/src/Internal/Checkout/JavaScriptPattern.php b/plugins/woocommerce/src/Internal/Checkout/JavaScriptPattern.php
new file mode 100644
index 00000000000..fca14bacbc6
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/Checkout/JavaScriptPattern.php
@@ -0,0 +1,465 @@
+<?php
+declare( strict_types = 1 );
+
+namespace Automattic\WooCommerce\Internal\Checkout;
+
+/**
+ * Finds constructs in a JSON Schema `pattern` that JavaScript rejects.
+ *
+ * PHP validates patterns with PCRE, while checkout uses JavaScript `u` mode.
+ * This conservative check identifies known incompatibilities for registration
+ * notices. The frontend falls back to server validation for affected fields.
+ *
+ * @internal
+ */
+final class JavaScriptPattern {
+
+ /**
+ * Escapes PCRE reads as an assertion or character class that `u` mode has no equivalent for.
+ *
+ * @var array<string, string>
+ */
+ private const PCRE_ONLY_ESCAPES = array(
+ 'A' => 'the "start of subject" assertion',
+ 'z' => 'the "end of subject" assertion',
+ 'Z' => 'the "end of subject" assertion',
+ 'G' => 'the "first matching position" assertion',
+ 'K' => 'the "keep out" reset',
+ 'h' => 'the horizontal whitespace class',
+ 'H' => 'the horizontal whitespace class',
+ 'R' => 'the line break sequence',
+ 'X' => 'the grapheme cluster class',
+ 'C' => 'the "single byte" class',
+ 'N' => 'the "non-newline" class',
+ 'a' => 'the "alarm" character',
+ 'e' => 'the "escape" character',
+ );
+
+ /**
+ * Punctuation a backslash may escape in `u` mode, both inside and outside a character class.
+ */
+ private const ESCAPABLE_PUNCTUATION = '^$\\.*+?()[]{}|/';
+
+ /**
+ * Escapes whose meaning changes inside a character class, and the ones that do not survive it.
+ *
+ * `\b` is a backspace inside a class, so it stays valid. `\B` and `\k` are
+ * assertions, which a class cannot contain.
+ */
+ private const CLASS_UNSAFE_ESCAPES = 'Bk';
+
+ /**
+ * Letters that introduce an escape requiring more characters after them.
+ */
+ private const TAIL_ESCAPES = 'cuxpP';
+
+ /**
+ * Other letters JavaScript accepts after a backslash in Unicode mode.
+ */
+ private const JS_ESCAPE_LETTERS = 'bBdDfnrsStvwWk';
+
+ /**
+ * Returns a description of the first construct `u` mode rejects, or null when it finds none.
+ *
+ * @param string $pattern The pattern, as written in a JSON Schema `pattern` keyword.
+ * @return string|null Description of the construct, or null when the pattern is usable.
+ */
+ public static function find_unsupported_construct( string $pattern ): ?string {
+ $length = strlen( $pattern );
+ $in_class = false;
+ $after_quantifier = false;
+ $group_assertions = array();
+ $capture_count = 0;
+ $max_reference = 0;
+
+ for ( $index = 0; $index < $length; $index++ ) {
+ $char = $pattern[ $index ];
+
+ if ( '\\' === $char ) {
+ $result = self::check_escape( $pattern, $index, $in_class );
+
+ if ( null !== $result ) {
+ return $result;
+ }
+
+ $escape = $pattern[ $index + 1 ];
+ $end = self::skip_escape_tail( $pattern, $index + 1, $escape );
+ if ( ! $in_class && ctype_digit( $escape ) && '0' !== $escape ) {
+ $max_reference = max( $max_reference, (int) substr( $pattern, $index + 1, $end - $index ) );
+ }
+
+ $index = $end;
+ $after_quantifier = false;
+ continue;
+ }
+
+ if ( '[' === $char ) {
+ // A class opened inside a class starts a POSIX class, as in [[:alpha:]].
+ if ( $in_class && $index + 1 < $length && ':' === $pattern[ $index + 1 ] ) {
+ return 'a POSIX character class, which JavaScript does not support';
+ }
+
+ $in_class = true;
+ $after_quantifier = false;
+ continue;
+ }
+
+ if ( $in_class ) {
+ if ( ']' === $char ) {
+ $in_class = false;
+ $after_quantifier = false;
+ }
+ continue;
+ }
+
+ // PCRE reads a stray bracket or brace as a literal, but `u` mode throws.
+ if ( ']' === $char || '}' === $char ) {
+ return 'a lone "' . $char . '", which JavaScript does not allow';
+ }
+
+ if ( '(' === $char ) {
+ $result = self::check_group_prefix( $pattern, $index );
+
+ if ( null !== $result ) {
+ return $result;
+ }
+
+ $prefix = substr( $pattern, $index + 1, 2 );
+ $is_assertion = in_array( $prefix, array( '?=', '?!' ), true ) || in_array( substr( $pattern, $index + 1, 3 ), array( '?<=', '?<!' ), true );
+ if ( '?' !== ( $pattern[ $index + 1 ] ?? '' ) || ( '?<' === $prefix && ! $is_assertion ) ) {
+ ++$capture_count;
+ }
+ $group_assertions[] = $is_assertion;
+
+ $after_quantifier = false;
+ continue;
+ }
+
+ if ( ')' === $char ) {
+ if ( true === array_pop( $group_assertions ) && $index + 1 < $length && self::quantifier_end( $pattern, $index + 1 ) >= 0 ) {
+ return 'a quantified lookaround assertion, which JavaScript does not support';
+ }
+
+ $after_quantifier = false;
+ continue;
+ }
+
+ if ( '+' === $char && $after_quantifier ) {
+ return 'a possessive quantifier, which JavaScript does not support';
+ }
+
+ $quantifier_end = self::quantifier_end( $pattern, $index );
+
+ if ( $quantifier_end >= 0 ) {
+ $after_quantifier = true;
+ $index = $quantifier_end;
+ continue;
+ }
+
+ if ( '{' === $char ) {
+ return 'an incomplete quantifier, which JavaScript does not support';
+ }
+
+ $after_quantifier = false;
+ }
+
+ if ( $in_class ) {
+ return 'an unterminated character class';
+ }
+
+ // Forward references are valid, so count all capturing groups before checking them.
+ if ( $max_reference > $capture_count ) {
+ return 'a numeric escape without a matching capture group, which JavaScript does not support';
+ }
+
+ return null;
+ }
+
+ /**
+ * Describes what `u` mode rejects about an escape, if anything.
+ *
+ * @param string $pattern The pattern.
+ * @param int $index Position of the backslash.
+ * @param bool $in_class Whether the escape sits inside a character class.
+ * @return string|null Description of the construct, or null when the escape is usable.
+ */
+ private static function check_escape( string $pattern, int $index, bool $in_class ): ?string {
+ $length = strlen( $pattern );
+
+ if ( $index + 1 >= $length ) {
+ return 'a trailing backslash';
+ }
+
+ $escape = $pattern[ $index + 1 ];
+
+ // `u` mode never allows escaping a non-ASCII character. Quote the whole
+ // character, since a single byte of it is not valid UTF-8.
+ if ( ord( $escape ) > 127 ) {
+ return '\\' . mb_substr( substr( $pattern, $index + 1 ), 0, 1, 'UTF-8' ) . ', an escape JavaScript does not allow';
+ }
+
+ if ( ctype_digit( $escape ) ) {
+ if ( $in_class && '0' !== $escape ) {
+ return 'a numeric escape inside a character class, which JavaScript does not support';
+ }
+
+ // A leading zero starts an octal escape, which `u` mode drops entirely.
+ if ( '0' === $escape && $index + 2 < $length && ctype_digit( $pattern[ $index + 2 ] ) ) {
+ return 'an octal escape, which JavaScript does not support';
+ }
+
+ return null;
+ }
+
+ if ( ctype_alpha( $escape ) ) {
+ if ( isset( self::PCRE_ONLY_ESCAPES[ $escape ] ) ) {
+ return '\\' . $escape . ', which JavaScript does not support as ' . self::PCRE_ONLY_ESCAPES[ $escape ];
+ }
+
+ if ( $in_class && false !== strpos( self::CLASS_UNSAFE_ESCAPES, $escape ) ) {
+ return '\\' . $escape . ' inside a character class, which JavaScript does not support';
+ }
+
+ if ( false !== strpos( self::TAIL_ESCAPES, $escape ) ) {
+ return self::check_escape_tail( $pattern, $index, $escape );
+ }
+
+ if ( 'k' === $escape && '<' !== ( $pattern[ $index + 2 ] ?? '' ) ) {
+ return '\\k without a name in angle brackets, which JavaScript does not support';
+ }
+
+ if ( false === strpos( self::JS_ESCAPE_LETTERS, $escape ) ) {
+ return '\\' . $escape . ', an escape JavaScript does not support';
+ }
+
+ return null;
+ }
+
+ if ( false !== strpos( self::ESCAPABLE_PUNCTUATION, $escape ) ) {
+ return null;
+ }
+
+ if ( $in_class && '-' === $escape ) {
+ return null;
+ }
+
+ // `u` mode only allows escaping syntax characters, so a backslash before
+ // a literal such as `-`, `@`, or a space throws.
+ return '\\' . $escape . ', an escape JavaScript does not allow ' . ( $in_class ? 'inside' : 'outside' ) . ' a character class';
+ }
+
+ /**
+ * Validates the characters an escape such as `\x`, `\u` or `\p` needs after it.
+ *
+ * @param string $pattern The pattern.
+ * @param int $index Position of the backslash.
+ * @param string $escape The character after the backslash.
+ * @return string|null Description of the construct, or null when the escape is usable.
+ */
+ private static function check_escape_tail( string $pattern, int $index, string $escape ): ?string {
+ $rest = (string) substr( $pattern, $index + 2 );
+
+ if ( 'c' === $escape ) {
+ return '' !== $rest && ctype_alpha( $rest[0] ) ? null : 'an incomplete control escape, which JavaScript does not support';
+ }
+
+ if ( 'x' === $escape ) {
+ $digits = substr( $rest, 0, 2 );
+
+ return 2 === strlen( $digits ) && ctype_xdigit( $digits ) ? null : 'an incomplete hex escape, which JavaScript does not support';
+ }
+
+ if ( 'u' === $escape ) {
+ if ( 0 === strpos( $rest, '{' ) ) {
+ return self::has_braced_hex( $rest, 0 ) ? null : 'an incomplete unicode escape, which JavaScript does not support';
+ }
+
+ $digits = substr( $rest, 0, 4 );
+
+ return 4 === strlen( $digits ) && ctype_xdigit( $digits ) ? null : 'an incomplete unicode escape, which JavaScript does not support';
+ }
+
+ // \p{...} and \P{...} need a property name in braces.
+ if ( 'p' === $escape || 'P' === $escape ) {
+ return self::has_braced_name( $rest ) ? null : 'an incomplete property escape, which JavaScript does not support';
+ }
+
+ return null;
+ }
+
+ /**
+ * Whether a brace opens at `$offset` and holds one or more hex digits up to `}`.
+ *
+ * @param string $text The text to inspect.
+ * @param int $offset Position of the opening brace.
+ * @return bool
+ */
+ private static function has_braced_hex( string $text, int $offset ): bool {
+ $close = strpos( $text, '}', $offset + 1 );
+
+ if ( false === $close || $close === $offset + 1 ) {
+ return false;
+ }
+
+ return ctype_xdigit( substr( $text, $offset + 1, $close - $offset - 1 ) );
+ }
+
+ /**
+ * Whether a `\p{...}` or `\P{...}` escape has a non-empty name in braces.
+ *
+ * @param string $text The text after the escape letter, starting at the brace.
+ * @return bool
+ */
+ private static function has_braced_name( string $text ): bool {
+ if ( 0 !== strpos( $text, '{' ) ) {
+ return false;
+ }
+
+ $close = strpos( $text, '}' );
+
+ return false !== $close && $close > 1;
+ }
+
+ /**
+ * Skips the fixed-length tail of a multi-character escape.
+ *
+ * @param string $pattern The pattern.
+ * @param int $start Position of the character after the backslash.
+ * @param string $escape The character after the backslash.
+ * @return int Position of the last character the escape consumes.
+ */
+ private static function skip_escape_tail( string $pattern, int $start, string $escape ): int {
+ $length = strlen( $pattern );
+
+ if ( ( 'p' === $escape || 'P' === $escape ) && $start + 1 < $length && '{' === $pattern[ $start + 1 ] ) {
+ $close = strpos( $pattern, '}', $start + 2 );
+
+ return false === $close ? $length - 1 : $close;
+ }
+
+ if ( 'k' === $escape && $start + 1 < $length && '<' === $pattern[ $start + 1 ] ) {
+ $close = strpos( $pattern, '>', $start + 2 );
+
+ return false === $close ? $length - 1 : $close;
+ }
+
+ if ( 'u' === $escape ) {
+ if ( $start + 1 < $length && '{' === $pattern[ $start + 1 ] ) {
+ $close = strpos( $pattern, '}', $start + 2 );
+
+ return false === $close ? $length - 1 : $close;
+ }
+
+ return min( $start + 4, $length - 1 );
+ }
+
+ if ( 'x' === $escape ) {
+ return min( $start + 2, $length - 1 );
+ }
+
+ if ( 'c' === $escape ) {
+ return min( $start + 1, $length - 1 );
+ }
+
+ if ( ctype_digit( $escape ) ) {
+ $end = $start;
+
+ while ( $end + 1 < $length && ctype_digit( $pattern[ $end + 1 ] ) ) {
+ ++$end;
+ }
+
+ return $end;
+ }
+
+ return $start;
+ }
+
+ /**
+ * Returns the last position of a `{n}`, `{n,}` or `{n,m}` quantifier, or -1 when none starts here.
+ *
+ * @param string $pattern The pattern.
+ * @param int $index Position to check.
+ * @return int The last position of the quantifier, or -1.
+ */
+ private static function quantifier_end( string $pattern, int $index ): int {
+ $char = $pattern[ $index ];
+
+ if ( '*' === $char || '+' === $char || '?' === $char ) {
+ return $index;
+ }
+
+ if ( '{' !== $char ) {
+ return -1;
+ }
+
+ if ( 1 === preg_match( '/^\{[0-9]+(?:,[0-9]*)?\}/', (string) substr( $pattern, $index ), $matches ) ) {
+ return $index + strlen( $matches[0] ) - 1;
+ }
+
+ return -1;
+ }
+
+ /**
+ * Describes what `u` mode rejects about a `(?`-style group, if anything.
+ *
+ * @param string $pattern The pattern.
+ * @param int $index Position of the `(`.
+ * @return string|null Description of the construct, or null when the group is usable.
+ */
+ private static function check_group_prefix( string $pattern, int $index ): ?string {
+ $length = strlen( $pattern );
+
+ if ( $index + 1 >= $length || '?' !== $pattern[ $index + 1 ] ) {
+ return null;
+ }
+
+ $after = $index + 2 < $length ? $pattern[ $index + 2 ] : '';
+ $rest = (string) substr( $pattern, $index + 2 );
+
+ // Non-capturing groups and both lookaheads are supported in `u` mode.
+ if ( ':' === $after || '=' === $after || '!' === $after ) {
+ return null;
+ }
+
+ // (?<= lookbehind, (?<! negative lookbehind, (?<name> named capture.
+ if ( '<' === $after ) {
+ return null;
+ }
+
+ // An inline modifier group only exists with a colon, as in (?i:...), and
+ // `u` mode only knows the i, m and s modifiers.
+ if ( 1 === preg_match( '/^[ims]*(?:-[ims]+)?:/', $rest ) ) {
+ return null;
+ }
+
+ if ( 1 === preg_match( '/^[ims]*(?:-[ims]+)?\)/', $rest ) ) {
+ return 'an inline flag, which JavaScript does not support';
+ }
+
+ if ( 1 === preg_match( '/^[A-Za-z-]+[:)]/', $rest ) ) {
+ return 'the "' . $after . '" modifier, which JavaScript does not support';
+ }
+
+ if ( 'P' === $after ) {
+ return 'a PCRE named group, which JavaScript does not support';
+ }
+
+ if ( '#' === $after ) {
+ return 'a comment group, which JavaScript does not support';
+ }
+
+ if ( '>' === $after ) {
+ return 'an atomic group, which JavaScript does not support';
+ }
+
+ if ( '|' === $after ) {
+ return 'a branch reset group, which JavaScript does not support';
+ }
+
+ if ( 'R' === $after ) {
+ return 'a recursion group, which JavaScript does not support';
+ }
+
+ return 'a group syntax that JavaScript does not support';
+ }
+}
diff --git a/plugins/woocommerce/tests/php/src/Blocks/Domain/Services/CheckoutFieldsSchema/ValidationTest.php b/plugins/woocommerce/tests/php/src/Blocks/Domain/Services/CheckoutFieldsSchema/ValidationTest.php
index 2f22fa9a100..26fee496f8e 100644
--- a/plugins/woocommerce/tests/php/src/Blocks/Domain/Services/CheckoutFieldsSchema/ValidationTest.php
+++ b/plugins/woocommerce/tests/php/src/Blocks/Domain/Services/CheckoutFieldsSchema/ValidationTest.php
@@ -22,6 +22,7 @@ class ValidationTest extends WP_UnitTestCase {
* [{"format": "date", "formatMaximum": "2026-02-30"}, "/formatMaximum", "date"]
* [{"format": "date", "formatMinimum": {"$data": "not-a-pointer"}}, "/formatMinimum/$data", "json-pointer"]
* [{"anyOf": [{"maxLength": -1}]}, "/anyOf/0/maxLength", "0"]
+ * [{"pattern": "["}, "/pattern", "regex"]
*
* @param array $rules The invalid schema.
* @param string $path The expected keyword path.
@@ -38,6 +39,28 @@ class ValidationTest extends WP_UnitTestCase {
$this->assertStringNotContainsString( '{properties}', $message );
}
+ /**
+ * @testdox PHP-valid schemas with browser-incompatible patterns produce a separate warning with the keyword path.
+ *
+ * @testWith [{"anyOf": [{"not": {"properties": {"pattern": {"pattern": "\\@"}}}}]}, "/anyOf/0/not/properties/pattern/pattern"]
+ * [{"items": {"pattern": "\\@"}}, "/items/pattern"]
+ * [{"items": [{"pattern": "\\@"}]}, "/items/0/pattern"]
+ * [{"patternProperties": {"^[a-z]+\\-$": {"type": "string"}}}, "/patternProperties"]
+ *
+ * @param array $rules The schema with a browser-incompatible pattern.
+ * @param string $path The expected keyword path.
+ */
+ public function test_browser_incompatible_patterns_preserve_valid_schema( array $rules, string $path ): void {
+ $this->assertTrue( Validation::is_valid_schema( $rules ), 'Browser compatibility must not invalidate a PHP-valid schema.' );
+ $warning = Validation::find_unsupported_pattern( $rules );
+
+ $this->assertWPError( $warning );
+ $message = $warning->get_error_message();
+ $this->assertStringContainsString( 'At "' . $path . '"', $message );
+ $this->assertStringContainsString( 'JavaScript', $message );
+ $this->assertStringNotContainsString( '/properties/test', $message );
+ }
+
/**
* @testdox A $data reference is accepted wherever the keyword's own value would be.
*
diff --git a/plugins/woocommerce/tests/php/src/Blocks/Domain/Services/CheckoutFieldsTest.php b/plugins/woocommerce/tests/php/src/Blocks/Domain/Services/CheckoutFieldsTest.php
index 3d3c962bc8b..5db15daa93d 100644
--- a/plugins/woocommerce/tests/php/src/Blocks/Domain/Services/CheckoutFieldsTest.php
+++ b/plugins/woocommerce/tests/php/src/Blocks/Domain/Services/CheckoutFieldsTest.php
@@ -430,6 +430,116 @@ class CheckoutFieldsTest extends WP_UnitTestCase {
$this->assertArrayHasKey( 'plugin-namespace/check-out', $this->controller->get_additional_fields(), 'A $data reference in a validation rule should not be rejected as an invalid schema.' );
}
+ /**
+ * @testdox A field whose pattern JavaScript cannot compile is registered with a warning and keeps its rules.
+ *
+ * @testWith ["^[0-9]{3}\\-[0-9]{4}$"]
+ * ["(?i)^abc$"]
+ * ["^\\@x$"]
+ * ["\\Aabc\\z"]
+ * ["^a++$"]
+ * ["^[[:alpha:]]+$"]
+ * ["^A\\-", "required"]
+ * ["^A\\-", "hidden"]
+ *
+ * @param string $pattern The pattern the browser cannot compile.
+ * @param string $rule_field The field option containing the pattern.
+ */
+ public function test_field_with_pattern_javascript_rejects_is_registered( string $pattern, string $rule_field = 'validation' ): void {
+ $this->setExpectedIncorrectUsage( 'woocommerce_register_additional_checkout_field' );
+ $rules = array(
+ 'type' => 'string',
+ 'pattern' => $pattern,
+ );
+ if ( 'validation' !== $rule_field ) {
+ $rules = array(
+ 'checkout' => array(
+ 'properties' => array(
+ 'customer_note' => $rules,
+ ),
+ ),
+ );
+ }
+
+ woocommerce_register_additional_checkout_field(
+ array(
+ 'id' => 'plugin-namespace/unsupported-pattern',
+ 'label' => 'Unsupported pattern',
+ 'location' => 'order',
+ $rule_field => $rules,
+ )
+ );
+
+ $fields = $this->controller->get_additional_fields();
+ $this->assertArrayHasKey( 'plugin-namespace/unsupported-pattern', $fields, 'A pattern the browser cannot compile must not block registration.' );
+ $registered_pattern = 'validation' === $rule_field
+ ? $fields['plugin-namespace/unsupported-pattern']['validation']['pattern']
+ : $fields['plugin-namespace/unsupported-pattern'][ $rule_field ]['checkout']['properties']['customer_note']['pattern'];
+ $this->assertSame( $pattern, $registered_pattern, 'The original pattern must remain available for server-side validation.' );
+ }
+
+ /**
+ * @testdox A pattern both engines accept does not block registration.
+ */
+ public function test_field_with_pattern_both_engines_accept_is_registered(): void {
+ woocommerce_register_additional_checkout_field(
+ array(
+ 'id' => 'plugin-namespace/supported-pattern',
+ 'label' => 'Supported pattern',
+ 'location' => 'order',
+ 'validation' => array(
+ 'type' => 'string',
+ 'pattern' => '^[A-Z]{2}[0-9]{8,12}$',
+ ),
+ )
+ );
+
+ $this->assertArrayHasKey( 'plugin-namespace/supported-pattern', $this->controller->get_additional_fields(), 'A pattern both engines accept must remain registered.' );
+ }
+
+ /**
+ * @testdox An unsupported pattern in a $data reference is not read as a pattern.
+ */
+ public function test_unsupported_pattern_behind_data_reference_is_ignored(): void {
+ woocommerce_register_additional_checkout_field(
+ array(
+ 'id' => 'plugin-namespace/pattern-from-field',
+ 'label' => 'Pattern from another field',
+ 'location' => 'order',
+ 'validation' => array(
+ 'type' => 'string',
+ 'pattern' => array( '$data' => '1/plugin~1other-field' ),
+ ),
+ )
+ );
+
+ $this->assertArrayHasKey( 'plugin-namespace/pattern-from-field', $this->controller->get_additional_fields(), 'A $data pointer must not be checked as a literal pattern.' );
+ }
+
+ /**
+ * @testdox Schema instance data with a property named pattern does not block registration.
+ */
+ public function test_pattern_in_instance_data_does_not_block_registration(): void {
+ $value = array( 'pattern' => '\\@' );
+
+ woocommerce_register_additional_checkout_field(
+ array(
+ 'id' => 'plugin-namespace/pattern-in-data',
+ 'label' => 'Pattern in data',
+ 'location' => 'order',
+ 'validation' => array(
+ 'type' => 'object',
+ 'const' => $value,
+ 'enum' => array( $value ),
+ 'default' => $value,
+ 'examples' => array( $value ),
+ ),
+ )
+ );
+
+ $this->assertArrayHasKey( 'plugin-namespace/pattern-in-data', $this->controller->get_additional_fields(), 'Instance data must not be checked as a regular expression.' );
+ }
+
/**
* @testdox Date comparison schemas default to date strings and keep supplied keywords.
*
diff --git a/plugins/woocommerce/tests/php/src/Internal/Checkout/JavaScriptPatternTest.php b/plugins/woocommerce/tests/php/src/Internal/Checkout/JavaScriptPatternTest.php
new file mode 100644
index 00000000000..b0a5100d5b2
--- /dev/null
+++ b/plugins/woocommerce/tests/php/src/Internal/Checkout/JavaScriptPatternTest.php
@@ -0,0 +1,154 @@
+<?php
+declare( strict_types = 1 );
+
+namespace Automattic\WooCommerce\Tests\Internal\Checkout;
+
+use Automattic\WooCommerce\Internal\Checkout\JavaScriptPattern;
+use WC_Unit_Test_Case;
+
+/**
+ * Tests for the JavaScriptPattern class.
+ */
+class JavaScriptPatternTest extends WC_Unit_Test_Case {
+
+ /**
+ * @testdox Patterns JavaScript rejects in `u` mode are reported.
+ *
+ * @testWith ["^[0-9]{3}\\-[0-9]{4}$"]
+ * ["(?i)^abc$"]
+ * ["^\\@x$"]
+ * ["\\Aabc\\z"]
+ * ["^a++$"]
+ * ["^[[:alpha:]]+$"]
+ * ["a*+"]
+ * ["a{2}+"]
+ * ["\\z"]
+ * ["\\Z"]
+ * ["\\h"]
+ * ["\\R"]
+ * ["(?>a)"]
+ * ["(?#comment)a"]
+ * ["(?P<name>a)"]
+ * ["[\\B]"]
+ * ["a}"]
+ * ["a]"]
+ * ["a\\"]
+ * ["\\00"]
+ * ["\\x4"]
+ * ["\\u12"]
+ * ["\\u{}"]
+ * ["\\pL"]
+ * ["\\c1"]
+ * ["[\\k]"]
+ * ["a{"]
+ * ["(?x)"]
+ * ["(?-i)"]
+ * ["(?R)"]
+ * ["(?|a)"]
+ * ["(?=a)+"]
+ * ["(?=a)*"]
+ * ["\\10"]
+ * ["[\\1]"]
+ * ["\\V"]
+ * ["\\Qa\\E"]
+ * ["(a)\\g1"]
+ * ["\\o{101}"]
+ * ["(?<n>a)\\k'n'"]
+ * ["(a)(?1)"]
+ * ["(?&n)(?<n>a)"]
+ * ["(?'n'a)"]
+ * ["(a)(?(1)a|b)"]
+ *
+ * @param string $pattern The pattern to check.
+ */
+ public function test_unsupported_patterns_are_reported( string $pattern ): void {
+ $this->assertNotNull(
+ JavaScriptPattern::find_unsupported_construct( $pattern ),
+ sprintf( 'The pattern "%s" should be reported as unsupported by JavaScript.', $pattern )
+ );
+ }
+
+ /**
+ * @testdox Patterns built from the tokens both engines accept are left alone.
+ *
+ * @testWith ["^[0-9]{5}$"]
+ * ["^[A-Z]{2}[0-9]{8,12}$"]
+ * ["^\\+?[0-9 ]{7,15}$"]
+ * ["^[\\p{L} '-]+$"]
+ * ["^\\w+$"]
+ * ["^\\d+$"]
+ * ["^\\s*$"]
+ * ["^(?:a|b)+$"]
+ * ["(?<name>a)\\k<name>"]
+ * ["(?<=a)b"]
+ * ["a+?"]
+ * ["[\\-]"]
+ * ["[^<>()]*"]
+ * ["\\$1\\.00"]
+ * ["^\\u0041$"]
+ * ["(?i:abc)"]
+ * [""]
+ * ["\\u{1}"]
+ * ["\\u{A}"]
+ * ["\\u{1F600}"]
+ * ["\\p{Script=Greek}"]
+ * ["(?i-s:a)"]
+ * ["\\cA"]
+ * ["\\0"]
+ * ["[\\0]"]
+ * ["\\10(a)(b)(c)(d)(e)(f)(g)(h)(i)(?<tenth>j)"]
+ * ["(?:(?=a))+"]
+ * ["\\b\\B\\d\\D\\f\\n\\r\\s\\S\\t\\v\\w\\W"]
+ *
+ * @param string $pattern The pattern to check.
+ */
+ public function test_supported_patterns_are_left_alone( string $pattern ): void {
+ $this->assertNull(
+ JavaScriptPattern::find_unsupported_construct( $pattern ),
+ sprintf( 'The pattern "%s" is valid ECMA-262 and should not be reported.', $pattern )
+ );
+ }
+
+ /**
+ * @testdox A report names the construct, so the message can say what to change.
+ */
+ public function test_report_describes_the_construct(): void {
+ $this->assertStringContainsString(
+ '\\-',
+ JavaScriptPattern::find_unsupported_construct( '^[0-9]{3}\\-[0-9]{4}$' )
+ );
+
+ $this->assertStringContainsString(
+ 'inline flag',
+ JavaScriptPattern::find_unsupported_construct( '(?i)^abc$' )
+ );
+
+ $this->assertStringContainsString(
+ 'possessive quantifier',
+ JavaScriptPattern::find_unsupported_construct( '^a++$' )
+ );
+
+ $this->assertStringContainsString(
+ '\\é',
+ JavaScriptPattern::find_unsupported_construct( '^[a-z]\\é$' ),
+ 'A non-ASCII escape must be quoted as a whole character.'
+ );
+ }
+
+ /**
+ * @testdox A character class is not read as pattern syntax.
+ */
+ public function test_character_class_contents_are_not_read_as_syntax(): void {
+ // The `+` and `{` inside the class are literals, not quantifiers.
+ $this->assertNull( JavaScriptPattern::find_unsupported_construct( '^[+{]+$' ) );
+ // A `-` may be escaped inside a class, even though `\-` throws outside one.
+ $this->assertNull( JavaScriptPattern::find_unsupported_construct( '^[\\-+]$' ) );
+ }
+
+ /**
+ * @testdox An unterminated class is reported, since `u` mode throws on it.
+ */
+ public function test_unterminated_class_is_reported(): void {
+ $this->assertNotNull( JavaScriptPattern::find_unsupported_construct( '^[a-z$' ) );
+ }
+}