URIフォーマット検証 — JSON Schemaでurl/URIを検証

JSON Schemaの format キーワードを使用してURI/URLの形式を検証する方法を解説します。

String Constraints

JSON Schema

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "properties": {
    "homepage": {
      "type": "string",
      "format": "uri",
      "pattern": "^https?://"
    },
    "profileImage": {
      "type": "string",
      "format": "uri"
    },
    "callbackPath": {
      "type": "string",
      "format": "uri-reference"
    }
  },
  "required": ["homepage"]
}

Test Data

{
  "homepage": "https://example.com/about",
  "profileImage": "https://cdn.example.com/images/avatar.png",
  "callbackPath": "/api/callback?code=abc123"
}

詳細な説明

JSON Schemaの format: "uri" キーワードは、文字列がRFC 3986に準拠した完全なURIであるかを検証します。関連するフォーマットとして uri-reference もあります。

URIフォーマットの種類:

  • uri: 完全修飾URI(https://example.com/path など)
  • uri-reference: 相対参照も含むURI(/path/to/resource#fragment も有効)
  • iri: 国際化リソース識別子(Unicode文字を含むURI)
  • iri-reference: IRIの相対参照版

完全なURIバリデーションでは、スキーム(httpsなど)が必須です。Webhook URLやコールバックURLの検証では uri フォーマットが適切です。相対パスも許可する場合は uri-reference を使用します。

ユースケース

Webhook URL、APIエンドポイント、外部リソースへのリンクなどのURLフィールドを検証する際に使用します。

試してみる — JSON Schema Validator

フルツールを開く