Define Enum Constraints in YAML Schema

Learn how to restrict JSON string and number fields to a fixed set of allowed values using YAML Schema enum constraints. Covers enum arrays, const for single values, and combining with other validations.

Validation Rules

Detailed Explanation

Enum Constraints in YAML Schema

The enum keyword restricts a field to a predefined set of allowed values. When converting JSON to YAML Schema, the converter identifies fields that match known patterns and suggests enum constraints.

Example JSON Input

{
  "environment": "production",
  "logLevel": "warn",
  "region": "us-east-1",
  "protocol": "https"
}

Generated YAML Schema

type: object
properties:
  environment:
    type: string
    enum: [development, staging, production]
  logLevel:
    type: string
    enum: [trace, debug, info, warn, error, fatal]
  region:
    type: string
    enum:
      - us-east-1
      - us-west-2
      - eu-west-1
      - eu-central-1
      - ap-northeast-1
  protocol:
    type: string
    enum: [http, https]
required:
  - environment
  - logLevel
  - region

Enum vs Const

For fields that must have exactly one value, use const:

apiVersion:
  type: string
  const: "v2"

This is equivalent to enum: ["v2"] but more explicit about the intent.

Enum with Default

logLevel:
  type: string
  enum: [trace, debug, info, warn, error, fatal]
  default: info

Numeric Enums

Enum works with any type, not just strings:

priority:
  type: integer
  enum: [1, 2, 3, 4, 5]
  description: "1=critical, 5=low"

Enum with Description Annotations

For better documentation, combine enum with description:

environment:
  type: string
  enum: [development, staging, production]
  description: |
    The deployment environment:
    - development: local development with debug features
    - staging: pre-production testing environment
    - production: live user-facing environment

Combining Enum with Other Constraints

region:
  type: string
  enum: [us-east-1, us-west-2, eu-west-1]
  pattern: "^[a-z]{2}-[a-z]+-\\d+$"

The pattern constraint is redundant here but documents the format for future enum additions.

Validation Error Messages

When a value doesn't match the enum, validators report:

Error: Value "staging2" is not one of the allowed values:
  development, staging, production
  at path '/environment'

When to Use Enum vs Pattern

  • Enum: When the complete set of valid values is known and small (< 20 items)
  • Pattern: When values follow a format but the exact set is large or evolving
  • Both: When you want format documentation alongside a fixed list

Use Case

Cloud infrastructure configuration commonly restricts values to specific regions, instance types, and environments. YAML schema enum constraints catch typos like 'prodution' or invalid regions like 'us-east-3' during CI validation, preventing costly deployment errors that would only surface at runtime.

Try It — JSON to YAML Schema

Open full tool