0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Zodとは?

Zod(ゾッド) = 入力チェック(バリデーション)を簡単に書けるライブラリ

ライブラリとは「便利な機能をまとめたツール集」!
「このデータは正しい形か?」をコードで保証する
APIレスポンス・フォーム入力のチェックによく使うらしい

シンプルなサンプル

import { z } from 'zod';

// ユーザーの形を定義
const UserSchema = z.object({
  id: z.number(),
  name: z.string(),
  display_name: z.string(),
});

// 型としても使える
type User = z.infer<typeof UserSchema>;

使いどころ(例)

const data = {
  id: 1,
  name: '山田',
  display_name: '山田さん',
};

// チェック(失敗すると例外)
const user = UserSchema.parse(data);

ここで何が起きてる?

OK → user が使える
NG(型違い・不足) → エラー
「怪しいデータをアプリに入れない」安全装置

// これがZodのバリデーション!
const UserDefinedTermUpdateSchema = z.object({
    display_name: z.string().max(20).nullable().optional(),
    //            ↑文字列  ↑最大20文字  ↑nullもOK  ↑なくてもOK
});

z.object() の中に「このデータはこういうルールですよ」を書いていくだけです。

Zodのルールの書き方

z.string()          // 文字列
z.string().min(1)   // 1文字以上
z.string().max(20)  // 20文字以内
z.number()          // 数値
z.boolean()         // true/false
z.nullable()        // nullもOK
z.optional()        // なくてもOK(undefined)

実際に使う時はこう書く

// ① スキーマ(ルール)を定義
const Schema = z.object({
    name: z.string().min(1, '名前は必須です').max(20, '20文字以内で入力してください'),
    age:  z.number().min(0).max(150),
});

// ② チェックする(safeParse)
const result = Schema.safeParse({ name: '', age: 25 });

if (!result.success) {
    //  バリデーション失敗
    console.log(result.error.issues[0].message); // → 「名前は必須です」
} else {
    // バリデーション成功
    console.log(result.data); // → { name: '', age: 25 }
}

まとめ

言葉 意味
バリデーション 入力値が正しいかチェックすること
Zod バリデーションを簡単に書けるライブラリ
スキーマ 「どんなルールでチェックするか」の定義
safeParse 実際にチェックを実行するメソッド(関数)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?