1
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?

More than 1 year has passed since last update.

【Zod】バリデーション前にデータを変換する方法

Last updated at Posted at 2024-03-25

.preprocess()を使用することで、スキーマのバリデーション前にデータを変換できます。

使用方法

.preprocess()は、引数として関数を受け取ります。この関数は、バリデーション前の元のデータを引数として受け取り、変換後のデータを返します。

const castToString = z.preprocess((val) => String(val), z.string())

console.log(castToString.parse(123));  // '123'
console.log(castToString.parse(true));  // 'true'
console.log(castToString.parse({foo: 'bar'}));  // '[object Object]'

上記のようにデータの型を強制するだけであればcoerceが使用できます。

const schema = z.coerce.string()

schema.parse("tuna"); // => "tuna"
schema.parse(12); // => "12"

1
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
1
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?