1
1
mirror of https://github.com/theoludwig/react-component-form.git synced 2024-07-17 07:30:13 +02:00
react-component-form/example/hooks/useFormTranslation.ts

52 lines
1.3 KiB
TypeScript
Raw Permalink Normal View History

import useTranslation from "next-translate/useTranslation"
import type { Error } from "react-component-form"
2022-08-26 20:19:31 +02:00
const knownErrorKeywords = ["minLength", "maxLength", "format"]
2022-08-26 20:19:31 +02:00
const getErrorTranslationKey = (error: Error): string => {
if (knownErrorKeywords.includes(error?.keyword)) {
if (
error.keyword === "minLength" &&
typeof error.data === "string" &&
2022-08-26 20:19:31 +02:00
error.data.length === 0
) {
return "common:required"
2022-08-26 20:19:31 +02:00
}
if (error.keyword === "format") {
if (error.params["format"] === "email") {
return "common:invalid-email"
2022-08-26 20:19:31 +02:00
}
return "common:invalid"
2022-08-26 20:19:31 +02:00
}
return `common:${error.keyword}`
}
return "common:invalid"
2022-08-26 20:19:31 +02:00
}
export const useFormTranslation = () => {
const { t } = useTranslation()
const getErrorTranslation = (
error: Error | undefined,
2022-08-26 20:19:31 +02:00
): string | undefined => {
if (error != null) {
return t(getErrorTranslationKey(error)).replace(
"{expected}",
error?.params?.["limit"],
2022-08-26 20:19:31 +02:00
)
}
return undefined
}
const getFirstErrorTranslation = (
errors: Error[] | undefined,
2022-08-26 20:19:31 +02:00
): string | undefined => {
if (errors != null) {
return getErrorTranslation(errors[0])
}
return undefined
}
return { getFirstErrorTranslation, getErrorTranslation }
}