🌐
zodのエラーメッセージの日本語化とカスタマイズ
zodに入門しました。
型生成できたり、preprocess
とか便利ですね😎
zodのエラーメッセージをカスタマイズする日本語の記事がなかったので色々調べてみた
ついでにNext.jsのi18nと連携してみた
リポジトリ
デモ
デモではchakraとreact-hook-formを使っています。
オリジナルなエラーメッセージ
公式より
// optional custom error message
z.string().nonempty({ message: "Can't be empty" });
オブジェクトのkeyをmessageにしてvalueを好きな値にすればいけるんですね🥰
デフォルトのエラーメッセージ
zodのエラーメッセージはすべて英語で定義されています
Required
(必須)などはどこでカスタマイズ(日本語化)するのだろう🤔
公式のエラーメッセージカスタマイズを読と・・・
公式より
import { z } from "zod";
const customErrorMap: z.ZodErrorMap = (issue, ctx) => {
if (issue.code === z.ZodIssueCode.invalid_type) {
if (issue.expected === "string") {
return { message: "bad type!" };
}
}
if (issue.code === z.ZodIssueCode.custom) {
return { message: `less-than-${(issue.params || {}).minimum}` };
}
return { message: ctx.defaultError };
};
z.setErrorMap(customErrorMap);
ほーん
・・・
・・・
Requiredはどこから変えるのだ?🥲
わからないので、Required
をgithubから探したら該当の箇所を見つけた
つまり、このswitchで書かれている部分を上のエラーメッセージカスタマイズといい感じにすれば良いわけである😎
switch (issue.code) {
case ZodIssueCode.invalid_type:
if (issue.received === "undefined") {
message = "Required";
} else {
message = `Expected ${issue.expected}, received ${issue.received}`;
}
break;
case ZodIssueCode.unrecognized_keys:
message = `Unrecognized key(s) in object: ${issue.keys
.map((k) => `'${k}'`)
.join(", ")}`;
break;
case ZodIssueCode.invalid_union:
message = `Invalid input`;
break;
case ZodIssueCode.invalid_union_discriminator:
message = `Invalid discriminator value. Expected ${issue.options
.map((val) => (typeof val === "string" ? `'${val}'` : val))
.join(" | ")}`;
break;
case ZodIssueCode.invalid_enum_value:
message = `Invalid enum value. Expected ${issue.options
.map((val) => (typeof val === "string" ? `'${val}'` : val))
.join(" | ")}`;
break;
case ZodIssueCode.invalid_arguments:
message = `Invalid function arguments`;
break;
case ZodIssueCode.invalid_return_type:
message = `Invalid function return type`;
break;
case ZodIssueCode.invalid_date:
message = `Invalid date`;
break;
case ZodIssueCode.invalid_string:
if (issue.validation !== "regex") message = `Invalid ${issue.validation}`;
else message = "Invalid";
break;
case ZodIssueCode.too_small:
if (issue.type === "array")
message = `Array must contain ${
issue.inclusive ? `at least` : `more than`
} ${issue.minimum} element(s)`;
else if (issue.type === "string")
message = `String must contain ${
issue.inclusive ? `at least` : `over`
} ${issue.minimum} character(s)`;
else if (issue.type === "number")
message = `Number must be greater than ${
issue.inclusive ? `or equal to ` : ``
}${issue.minimum}`;
else message = "Invalid input";
break;
case ZodIssueCode.too_big:
if (issue.type === "array")
message = `Array must contain ${
issue.inclusive ? `at most` : `less than`
} ${issue.maximum} element(s)`;
else if (issue.type === "string")
message = `String must contain ${
issue.inclusive ? `at most` : `under`
} ${issue.maximum} character(s)`;
else if (issue.type === "number")
message = `Number must be less than ${
issue.inclusive ? `or equal to ` : ``
}${issue.maximum}`;
else message = "Invalid input";
break;
case ZodIssueCode.custom:
message = `Invalid input`;
break;
case ZodIssueCode.invalid_intersection_types:
message = `Intersection results could not be merged`;
break;
case ZodIssueCode.not_multiple_of:
message = `Number must be a multiple of ${issue.multipleOf}`;
break;
default:
message = _ctx.defaultError;
util.assertNever(issue);
}
message = "XXXX"
をreturn { message: XXXX }
の形式に書き換える
tsx
switch (issue.code) {
case ZodIssueCode.invalid_type:
if (issue.received === "undefined") {
- message = "Required";
+ return {
+ message: '必須'
+ }
} else {
- message = `Expected ${issue.expected}, received ${issue.received}`;
+ return {
+ message: `Expected ${issue.expected}, received ${issue.received}`,
+ }
}
- break;
}
default
を{ message: ctx.defaultError }
としデフォルトのエラーを返すように変更する
tsx
switch (issue.code) {
default:
- message = _ctx.defaultError;
- util.assertNever(issue);
+ return { message: ctx.defaultError }
}
export const zodCustomErrorMap = (issue, ctx): z.ZodErrorMap => {
switch (issue.code) {
case z.ZodIssueCode.invalid_type:
if (issue.received === 'undefined') {
return {
message: '必須'
}
} else {
return {
message: `Expected ${issue.expected}, received ${issue.received}`,
}
}
case z.ZodIssueCode.unrecognized_keys:
return {
message: `Unrecognized key(s) in object: ${issue.keys
.map((k) => `'${k}'`)
.join(', ')}`,
}
case z.ZodIssueCode.invalid_union:
return {
message: `Invalid input`,
}
case z.ZodIssueCode.invalid_union_discriminator:
return {
message: `Invalid discriminator value. Expected ${issue.options
.map((val) => (typeof val === 'string' ? `'${val}'` : val))
.join(' | ')}`,
}
case z.ZodIssueCode.invalid_enum_value:
return {
message: `Invalid enum value. Expected ${issue.options
.map((val) => (typeof val === 'string' ? `'${val}'` : val))
.join(' | ')}`,
}
case z.ZodIssueCode.invalid_arguments:
return {
message: `Invalid function arguments`,
}
case z.ZodIssueCode.invalid_return_type:
return {
message: `Invalid function return type`,
}
case z.ZodIssueCode.invalid_date:
return {
message: `Invalid date`,
}
case z.ZodIssueCode.invalid_string:
if (issue.validation !== 'regex') {
return {
message: isJapanese
? `${issue.validation}は無効な形式です`
: ctx.defaultError,
}
} else {
return {
message: 'Invalid',
}
}
case z.ZodIssueCode.too_small:
if (issue.type === 'array') {
return {
message: `Array must contain ${
issue.inclusive ? `at least` : `more than`
} ${issue.minimum} element(s)`,
}
} else if (issue.type === 'string') {
return {
message: isJapanese
? issue.inclusive
? `文字列には少なくとも${issue.minimum}文字が含まれている必要があります`
: `文字列には${issue.minimum}文字以上が含まれている必要があります`
: ctx.defaultError,
}
} else if (issue.type === 'number') {
return {
message: `Number must be greater than ${
issue.inclusive ? `or equal to ` : ``
}${issue.minimum}`,
}
} else {
return { message: 'Invalid input' }
}
case z.ZodIssueCode.too_big:
if (issue.type === 'array') {
return {
message: `Array must contain ${
issue.inclusive ? `at most` : `less than`
} ${issue.maximum} element(s)`,
}
} else if (issue.type === 'string') {
return {
message: `String must contain ${
issue.inclusive ? `at most` : `under`
} ${issue.maximum} character(s)`,
}
} else if (issue.type === 'number') {
return {
message: `Number must be less than ${
issue.inclusive ? `or equal to ` : ``
}${issue.maximum}`,
}
} else {
return {
message: 'Invalid input',
}
}
case z.ZodIssueCode.custom:
return {
message: `Invalid input`,
}
case z.ZodIssueCode.invalid_intersection_types:
return {
message: `Intersection results could not be merged`,
}
case z.ZodIssueCode.not_multiple_of:
return {
message: `Number must be a multiple of ${issue.multipleOf}`,
}
default:
return { message: ctx.defaultError }
}
}
z.setErrorMap(zodCustomErrorMap())
のこりはいい感じにカスタマイズしてみてください😀
Nextと連携する
_app.tsx
import type { AppProps } from 'next/app'
import { useLocale } from '@src/hooks/useLocale'
import { zodCustomErrorMap } from '@src/libs/validation/zodCustomErrorMap'
import { z } from 'zod'
/**
* @see https://github.com/colinhacks/zod/blob/master/ERROR_HANDLING.md#global-error-map
* @see https://github.com/colinhacks/zod/blob/cbbfedd15ffbe7d880f52d6becb76dcaef54875f/src/ZodError.ts#L284
*/
function MyApp({ Component, pageProps }: AppProps) {
const { locale } = useLocale()
z.setErrorMap(zodCustomErrorMap(locale))
return (
<Component {...pageProps} />
)
}
export default MyApp
next.jsのデフォルトのi18nの設定をする
next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
/**
* @see https://nextjs.org/docs/advanced-features/i18n-routing
* @see https://zenn.dev/steelydylan/articles/nextjs-with-i18n
*/
i18n: {
locales: ['en', 'ja'],
defaultLocale: 'ja',
},
}
module.exports = nextConfig
localeを判定するhooksを作る
useLocale.ts
import { NextRouter, useRouter } from 'next/router'
const localeMap = (locale: NextRouter['locale']) => {
switch (locale) {
case 'ja':
return 'ja'
case 'en':
return 'en'
default:
return 'ja'
}
}
export const useLocale = (): {
isEnglish: boolean
isJapanese: boolean
locale: ReturnType<typeof localeMap>
} => {
const { locale: _locale } = useRouter()
const locale = localeMap(_locale)
const isJapanese = locale === 'ja'
const isEnglish = locale === 'en'
return {
isEnglish,
isJapanese,
locale,
}
}
export type UseLocaleResult = ReturnType<typeof useLocale>
zodCustomErrorMapにlocaleを受け取れるようにする
zodCustomErrorMap.ts
import { z } from 'zod'
import type { UseLocaleResult } from '@src/hooks/useLocale'
export const zodCustomErrorMap =
(locale: UseLocaleResult['locale']): z.ZodErrorMap =>
(issue, ctx) => {
const isJapanese = locale === 'ja'
/**
* enの場合はDefaultエラー内容を返す
*/
if (locale === 'en') {
return { message: ctx.defaultError }
}
switch (issue.code) {
case z.ZodIssueCode.invalid_type:
if (issue.received === 'undefined') {
return {
/**
* なんとなくisJapaneseの分岐を書いている
*/
message: isJapanese ? '必須' : ctx.defaultError,
}
} else {
return {
message: `Expected ${issue.expected}, received ${issue.received}`,
}
}
case z.ZodIssueCode.unrecognized_keys:
return {
message: `Unrecognized key(s) in object: ${issue.keys
.map((k) => `'${k}'`)
.join(', ')}`,
}
case z.ZodIssueCode.invalid_union:
return {
message: `Invalid input`,
}
case z.ZodIssueCode.invalid_union_discriminator:
return {
message: `Invalid discriminator value. Expected ${issue.options
.map((val) => (typeof val === 'string' ? `'${val}'` : val))
.join(' | ')}`,
}
case z.ZodIssueCode.invalid_enum_value:
return {
message: `Invalid enum value. Expected ${issue.options
.map((val) => (typeof val === 'string' ? `'${val}'` : val))
.join(' | ')}`,
}
case z.ZodIssueCode.invalid_arguments:
return {
message: `Invalid function arguments`,
}
case z.ZodIssueCode.invalid_return_type:
return {
message: `Invalid function return type`,
}
case z.ZodIssueCode.invalid_date:
return {
message: `Invalid date`,
}
case z.ZodIssueCode.invalid_string:
if (issue.validation !== 'regex') {
return {
message: isJapanese
? `${issue.validation}は無効な形式です`
: ctx.defaultError,
}
} else {
return {
message: 'Invalid',
}
}
case z.ZodIssueCode.too_small:
if (issue.type === 'array') {
return {
message: `Array must contain ${
issue.inclusive ? `at least` : `more than`
} ${issue.minimum} element(s)`,
}
} else if (issue.type === 'string') {
return {
message: isJapanese
? issue.inclusive
? `文字列には少なくとも${issue.minimum}文字が含まれている必要があります`
: `文字列には${issue.minimum}文字以上が含まれている必要があります`
: ctx.defaultError,
}
} else if (issue.type === 'number') {
return {
message: `Number must be greater than ${
issue.inclusive ? `or equal to ` : ``
}${issue.minimum}`,
}
} else {
return { message: 'Invalid input' }
}
case z.ZodIssueCode.too_big:
if (issue.type === 'array') {
return {
message: `Array must contain ${
issue.inclusive ? `at most` : `less than`
} ${issue.maximum} element(s)`,
}
} else if (issue.type === 'string') {
return {
message: `String must contain ${
issue.inclusive ? `at most` : `under`
} ${issue.maximum} character(s)`,
}
} else if (issue.type === 'number') {
return {
message: `Number must be less than ${
issue.inclusive ? `or equal to ` : ``
}${issue.maximum}`,
}
} else {
return {
message: 'Invalid input',
}
}
case z.ZodIssueCode.custom:
return {
message: `Invalid input`,
}
case z.ZodIssueCode.invalid_intersection_types:
return {
message: `Intersection results could not be merged`,
}
case z.ZodIssueCode.not_multiple_of:
return {
message: `Number must be a multiple of ${issue.multipleOf}`,
}
default:
return { message: ctx.defaultError }
}
}
まとめ
だれか全部翻訳パッケージ作ってくれ😂
今回使ったリポジトリ
Discussion