JSON Schema String Constraints — minLength, maxLength, pattern

Discover how to add string constraints like minLength, maxLength, and pattern to a generated JSON Schema. Tighten validation beyond basic type checks.

Basic Types

Detailed Explanation

Adding String Constraints to Generated Schemas

The basic generator infers "type": "string" from any string value, but real-world validation often requires tighter constraints. After generating the initial schema you can enhance string properties with several keywords.

Available String Keywords

Keyword Purpose Example
minLength Minimum character count "minLength": 1
maxLength Maximum character count "maxLength": 255
pattern Regex the value must match "pattern": "^[a-z]+$"
format Semantic format hint "format": "email"

Example: Enhancing a Username Field

Starting from a generated property:

{ "username": { "type": "string" } }

You might refine it to:

{
  "username": {
    "type": "string",
    "minLength": 3,
    "maxLength": 30,
    "pattern": "^[a-zA-Z0-9_]+$"
  }
}

This ensures the username is 3-30 characters long and contains only alphanumeric characters or underscores.

The format Keyword

The format keyword is an annotation that validators may enforce depending on configuration. Common values include "email", "uri", "date-time", "uuid", and "ipv4". Unlike pattern, format does not use a custom regex — the validator has built-in logic for each recognized format.

When to Use Each Keyword

  • Use minLength/maxLength for database column limits or UI field sizes.
  • Use pattern when the value must follow a specific syntax (e.g., slugs, codes, phone numbers).
  • Use format for well-known types that validators already understand, reducing the chance of a faulty regex.

Combining these keywords lets you go from a loose generated schema to a production-ready contract that catches invalid data before it reaches your application logic.

Use Case

Apply string constraints when building schemas for user registration forms, content management APIs, or any endpoint where free-text input must conform to specific length and format rules.

Try It — JSON Schema Generator

Open full tool