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