条件付きバリデーション — if/then/elseの使い方

JSON Schemaの if/then/else キーワードで条件分岐バリデーションを定義する方法を解説します。

Advanced

JSON Schema

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "properties": {
    "shippingType": {
      "type": "string",
      "enum": ["domestic", "international"]
    },
    "state": {
      "type": "string"
    },
    "country": {
      "type": "string"
    },
    "customsDeclaration": {
      "type": "boolean"
    },
    "zipCode": {
      "type": "string"
    }
  },
  "required": ["shippingType"],
  "if": {
    "properties": {
      "shippingType": { "const": "international" }
    },
    "required": ["shippingType"]
  },
  "then": {
    "required": ["country", "customsDeclaration"],
    "properties": {
      "customsDeclaration": { "const": true }
    }
  },
  "else": {
    "required": ["state", "zipCode"]
  }
}

Test Data

{
  "shippingType": "international",
  "country": "Germany",
  "customsDeclaration": true
}

詳細な説明

JSON Schema Draft 7で導入された if/then/else キーワードにより、条件分岐に基づくバリデーションが可能になりました。プログラミング言語のif文に類似した直感的な構文です。

基本構文:

{
  "type": "object",
  "properties": {
    "country": { "type": "string" },
    "postal_code": { "type": "string" }
  },
  "if": {
    "properties": { "country": { "const": "US" } },
    "required": ["country"]
  },
  "then": {
    "properties": { "postal_code": { "pattern": "^[0-9]{5}(-[0-9]{4})?$" } }
  },
  "else": {
    "properties": { "postal_code": { "pattern": "^[A-Z0-9 -]+$" } }
  }
}

この例では、国がUSの場合は米国の郵便番号形式を検証し、それ以外の場合はより一般的なパターンを適用します。

注意点:

  • else は省略可能です。
  • if/then/else をネストすることも可能ですが、読みにくくなるため allOf 内で複数の条件を並列に定義する方が推奨されます。

ユースケース

国別の郵便番号形式、支払い方法に応じた必須フィールド、ユーザータイプ別のバリデーションルールなどで使用します。

試してみる — JSON Schema Validator

フルツールを開く