Pattern Validation — Regex in JSON Schema

Apply regex patterns to JSON Schema properties using the pattern keyword. Validate formats like phone numbers, slugs, and codes with regular expressions.

Advanced Patterns

Detailed Explanation

Using Regex Patterns in JSON Schema

The pattern keyword applies a regular expression to string values. This is one of the most powerful validation tools in JSON Schema, letting you enforce custom formats beyond what format provides.

Syntax

{
  "slug": {
    "type": "string",
    "pattern": "^[a-z0-9]+(-[a-z0-9]+)*$"
  }
}

The regex follows ECMA-262 (JavaScript regex) syntax. The above pattern validates URL slugs like "my-post" or "hello-world-2024".

Important: Anchoring

JSON Schema does not implicitly anchor patterns. A pattern of [0-9]+ matches "abc123def" because it finds a substring match. To match the entire string, use ^ and $:

{ "pattern": "^[0-9]+$" }

The patternProperties Keyword

While pattern validates a property's value, patternProperties validates property names (keys):

{
  "type": "object",
  "patternProperties": {
    "^x-": { "type": "string" }
  }
}

This schema says: any property whose key starts with x- must have a string value. This is commonly used for extension fields in formats like OpenAPI.

Common Patterns

Use case Pattern
Hex color ^#[0-9a-fA-F]{6}$
Semantic version ^\\d+\\.\\d+\\.\\d+$
ISO date ^\\d{4}-\\d{2}-\\d{2}$
Phone (US) ^\\+1[2-9]\\d{9}$
Slug ^[a-z0-9]+(-[a-z0-9]+)*$

Generator Limitations

Generators cannot infer patterns from a single sample value. A value of "2024-01-15" will be typed as "string" without any pattern. You must add patterns manually or use an advanced generator that recognizes common formats and suggests appropriate patterns.

Performance Considerations

Complex patterns with heavy backtracking can slow down validation. Keep patterns as simple as possible, and avoid nested quantifiers like (a+)+ which can cause catastrophic backtracking.

Use Case

Use pattern validation for custom identifiers, product codes, version strings, file names, and any string field that must conform to a specific format not covered by the built-in format keyword.

Try It — JSON Schema Generator

Open full tool