💎 Zod 4 is now stable!  Read the announcement.
Zod logo

エラーのカスタマイズ (Customizing errors)

Zod では、バリデーションエラーは z.core.$ZodError クラスのインスタンスとして表面化されます。

zod パッケージの ZodError クラスは、いくつかの追加の便利なメソッドを実装するサブクラスです。

$ZodError のインスタンスには .issues 配列が含まれています。各 issue には、人間が読める message と、issue に関する追加の構造化メタデータが含まれています。

import * as z from "zod";
 
const result = z.string().safeParse(12); // { success: false, error: ZodError }
result.error.issues;
// [
//   {
//     expected: 'string',
//     code: 'invalid_type',
//     path: [],
//     message: 'Invalid input: expected string, received number'
//   }
// ]

すべての issue には、人間が読めるエラーメッセージを含む message プロパティが含まれています。エラーメッセージは、さまざまな方法でカスタマイズできます。

error パラメータ (The error param)

事実上すべての Zod API は、オプションのエラーメッセージを受け入れます。

z.string("Not a string!");

このカスタムエラーは、このスキーマから発生するすべてのバリデーション issue の message プロパティとして表示されます。

z.string("Not a string!").parse(12);
// ❌ throws ZodError {
//   issues: [
//     {
//       expected: 'string',
//       code: 'invalid_type',
//       path: [],
//       message: 'Not a string!'   <-- 👀 custom error message
//     }
//   ]
// }

すべての z 関数とスキーマメソッドは、カスタムエラーを受け入れます。

z.string("Bad!");
z.string().min(5, "Too short!");
z.uuid("Bad UUID!");
z.iso.date("Bad date!");
z.array(z.string(), "Not an array!");
z.array(z.string()).min(5, "Too few items!");
z.set(z.string(), "Bad set!");

必要に応じて、代わりに error パラメータを持つ params オブジェクトを渡すこともできます。

z.string({ error: "Bad!" });
z.string().min(5, { error: "Too short!" });
z.uuid({ error: "Bad UUID!" });
z.iso.date({ error: "Bad date!" });
z.array(z.string(), { error: "Bad array!" });
z.array(z.string()).min(5, { error: "Too few items!" });
z.set(z.string(), { error: "Bad set!" });

error パラメータは、オプションで関数を受け入れます。エラーカスタマイズ関数は、Zod の用語では エラーマップ (error map) と呼ばれます。エラーマップは、バリデーションエラーが発生した場合に解析時に実行されます。

z.string({ error: ()=>`[${Date.now()}]: Validation failure.` });

注意 — Zod v3 では、message(文字列)と errorMap(関数)に別々のパラメータがありました。これらは Zod 4 で error として統合されました。

エラーマップは、バリデーション issue に基づいてエラーメッセージをカスタマイズするために使用できるコンテキストオブジェクトを受け取ります。

z.string({
  error: (iss) => iss.input === undefined ? "Field is required." : "Invalid input."
});

高度なケースでは、iss オブジェクトは、エラーをカスタマイズするために使用できる追加情報を提供します。

z.string({
  error: (iss) => {
    iss.code; // the issue code
    iss.input; // the input data
    iss.inst; // the schema/check that originated this issue
    iss.path; // the path of the error
  },
});

使用している API に応じて、追加のプロパティが利用可能な場合があります。TypeScript のオートコンプリートを使用して、利用可能なプロパティを確認してください。

z.string().min(5, {
  error: (iss) => {
    // ...the same as above
    iss.minimum; // the minimum value
    iss.inclusive; // whether the minimum is inclusive
    return `Password must have ${iss.minimum} characters or more`;
  },
});

エラーメッセージのカスタマイズを避け、デフォルトのメッセージにフォールバックするには、undefined を返します。(より具体的には、Zod は 優先順位チェーン の次のエラーマップに制御を譲ります。)これは、特定のエラーメッセージを選択的にカスタマイズするが、他のエラーメッセージはカスタマイズしない場合に便利です。

z.int64({
  error: (issue) => {
    // override too_big error message
    if (issue.code === "too_big") {
      return { message: `Value must be <${issue.maximum}` };
    }
 
    //  defer to default
    return undefined;
  },
});

解析ごとのエラーカスタマイズ (Per-parse error customization)

解析ごと にエラーをカスタマイズするには、エラーマップを parse メソッドに渡します。

const schema = z.string();
 
schema.parse(12, {
  error: iss => "per-parse custom error"
});

これは、スキーマレベルのカスタムメッセージよりも 優先順位が低い です。

const schema = z.string({ error: "highest priority" });
const result = schema.safeParse(12, {
  error: (iss) => "lower priority",
});
 
result.error.issues;
// [{ message: "highest priority", ... }]

iss オブジェクトは、すべての可能な issue タイプの 判別共用体 です。それらを区別するには code プロパティを使用します。

すべての Zod issue コードの内訳については、zod/v4/core ドキュメントを参照してください。

const result = schema.safeParse(12, {
  error: (iss) => {
    if (iss.code === "invalid_type") {
      return `invalid type, expected ${iss.expected}`;
    }
    if (iss.code === "too_small") {
      return `minimum is ${iss.minimum}`;
    }
    // ...
  }
});

issue に入力を含める (Include input in issues)

デフォルトでは、Zod は issue に入力データを含めません。これは、機密性の高い入力データが意図せずログに記録されるのを防ぐためです。各 issue に入力データを含めるには、reportInput フラグを使用します。

z.string().parse(12, {
  reportInput: true
})
 
// ZodError: [
//   {
//     "expected": "string",
//     "code": "invalid_type",
//     "input": 12, // 👀
//     "path": [],
//     "message": "Invalid input: expected string, received number"
//   }
// ]

グローバルエラーカスタマイズ (Global error customization)

グローバルエラーマップを指定するには、z.config() を使用して Zod の customError 構成設定を設定します。

z.config({
  customError: (iss) => {
    return "globally modified error";
  },
});

グローバルエラーメッセージは、スキーマレベルまたは解析ごとのエラーメッセージよりも 優先順位が低い です。

iss オブジェクトは、すべての可能な issue タイプの 判別共用体 です。それらを区別するには code プロパティを使用します。

すべての Zod issue コードの内訳については、zod/v4/core ドキュメントを参照してください。

z.config({
  customError: (iss) => {
    if (iss.code === "invalid_type") {
      return `invalid type, expected ${iss.expected}`;
    }
    if (iss.code === "too_small") {
      return `minimum is ${iss.minimum}`;
    }
    // ...
  },
});

国際化 (Internationalization)

エラーメッセージの国際化をサポートするために、Zod はいくつかの組み込み ロケール を提供しています。これらは zod/v4/core パッケージからエクスポートされます。

注意 — 通常の zod ライブラリは、自動的に en ロケールをロードします。Zod Mini はデフォルトでどのロケールもロードしません。代わりにすべてのエラーメッセージはデフォルトで Invalid input になります。

import * as z from "zod";
import { en } from "zod/locales"
 
z.config(en());

ロケールを遅延ロードするには、動的インポートを検討してください:

import * as z from "zod";
 
async function loadLocale(locale: string) {
  const { default: locale } = await import(`zod/v4/locales/${locale}.js`);
  z.config(locale());
};
 
await loadLocale("fr");

便宜上、すべてのロケールは "zod" から z.locales としてエクスポートされます。一部のバンドラーでは、これは tree-shake できない場合があります。

import * as z from "zod";
 
z.config(z.locales.en());

ロケール (Locales)

以下のロケールが利用可能です:

  • ar — アラビア語
  • az — アゼルバイジャン語
  • be — ベラルーシ語
  • bg — ブルガリア語
  • ca — カタルーニャ語
  • cs — チェコ語
  • da — デンマーク語
  • de — ドイツ語
  • en — 英語
  • eo — エスペラント語
  • es — スペイン語
  • fa — ペルシャ語
  • fi — フィンランド語
  • fr — フランス語
  • frCA — カナダフランス語
  • he — ヘブライ語
  • hu — ハンガリー語
  • id — インドネシア語
  • is — アイスランド語
  • it — イタリア語
  • ja — 日本語
  • ka — ジョージア語
  • km — クメール語
  • ko — 韓国語
  • lt — リトアニア語
  • mk — マケドニア語
  • ms — マレー語
  • nl — オランダ語
  • no — ノルウェー語
  • ota — オスマン語
  • ps — パシュトー語
  • pl — ポーランド語
  • pt — ポルトガル語
  • ru — ロシア語
  • sl — スロベニア語
  • sv — スウェーデン語
  • ta — タミル語
  • th — タイ語
  • tr — トルコ語
  • uk — ウクライナ語
  • ur — ウルドゥー語
  • vi — ベトナム語
  • zhCN — 簡体字中国語
  • zhTW — 繁体字中国語
  • yo — ヨルバ語

エラーの優先順位 (Error precedence)

以下は、エラーの優先順位を決定するためのクイックリファレンスです。複数のエラーカスタマイズが定義されている場合、どれが優先されますか?優先順位の 高い順

  1. スキーマレベルのエラー — スキーマ定義に「ハードコード」されたエラーメッセージ。
z.string("Not a string!");
  1. 解析ごとのエラー.parse() メソッドに渡されたカスタムエラーマップ。
z.string().parse(12, {
  error: (iss) => "My custom error"
});
  1. グローバルエラーマップz.config() に渡されたカスタムエラーマップ。
z.config({
  customError: (iss) => "My custom error"
});
  1. ロケールエラーマップz.config() に渡されたカスタムエラーマップ。
z.config(z.locales.en());