依存する必須フィールド — dependentRequiredの使い方

JSON Schemaの dependentRequired キーワードで、あるフィールドの存在に依存して別のフィールドを必須にする方法を解説します。

Object Constraints

JSON Schema

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "properties": {
    "name": {
      "type": "string"
    },
    "creditCard": {
      "type": "string",
      "pattern": "^\\d{13,19}$"
    },
    "billingAddress": {
      "type": "string"
    },
    "couponCode": {
      "type": "string"
    },
    "couponSource": {
      "type": "string",
      "enum": ["email", "social", "partner"]
    }
  },
  "required": ["name"],
  "dependentRequired": {
    "creditCard": ["billingAddress"],
    "couponCode": ["couponSource"]
  }
}

Test Data

{
  "name": "Alice Chen",
  "creditCard": "4111111111111111",
  "billingAddress": "123 Main St, San Francisco, CA 94102",
  "couponCode": "SAVE20",
  "couponSource": "email"
}

詳細な説明

JSON Schemaの dependentRequired キーワードは、特定のプロパティが存在する場合に、他のプロパティも必須にするための条件付き必須制約を定義します。

基本構文:

{
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "credit_card": { "type": "string" },
    "billing_address": { "type": "string" }
  },
  "dependentRequired": {
    "credit_card": ["billing_address"]
  }
}

この例では、credit_card プロパティが存在する場合、billing_address も必須になります。しかし、credit_card が存在しない場合、billing_address は不要です。

dependentSchemas との違い:

  • dependentRequired: プロパティの存在のみを要求(シンプル)
  • dependentSchemas: より複雑な条件付きスキーマを適用可能

dependentRequired はJSON Schema Draft 2019-09で導入されました。それ以前のバージョンでは dependencies キーワードが使用されていました。

ユースケース

クレジットカード情報と請求先住所、配送方法と配送先住所など、条件付きで必須となるフィールドのバリデーションに使用します。

試してみる — JSON Schema Validator

フルツールを開く