【zod】NumericなStringをNumberに変換する
zodでNumericな(数字のみで構成される)文字列を取り扱いたい時がある。
const schema = z .string() .transform(Number);
schema.parse('123'); // 123schema.parse('hoge'); // NaN
上記のように文字列の判定をせずString → Numberに変換するともちろんNaN
となってしまうが、組み込みでnumeric()
のようなものは無い。
解決法
const schema = z .string() .regex(/^\d+$/, { message: '数値の文字列を入力してください' }) .transform(Number);
schema.parse('123'); // 123schema.parse('hoge'); // ZodError
regex()
で、数値のみで構成されているかを判定するのが手っ取り早そう。