Skip to content

Instantly share code, notes, and snippets.

@sawaYch
Created June 2, 2023 13:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sawaYch/c660963348d0f78b10eb0c01b70e06d4 to your computer and use it in GitHub Desktop.
Save sawaYch/c660963348d0f78b10eb0c01b70e06d4 to your computer and use it in GitHub Desktop.
override yup date() default typeError validation message
// https://github.com/jquense/yup/issues/394
import i18next from "i18next";
import { setLocale } from "yup";
export const setFormikLocale = (i18n: typeof i18next): void => {
// Config yup validation schema default error message
setLocale({
mixed: {
notType: (_ref) => {
let typeErrorMessageKey: string;
switch (_ref.type) {
case "date":
typeErrorMessageKey =
"Common.form.validationError.date.invalidFormat";
break;
default:
typeErrorMessageKey =
"Common.form.validationError.general.invalidFormat";
break;
}
return i18n.t(typeErrorMessageKey as unknown as TemplateStringsArray);
},
required: ({ label }) => {
const fieldLabel = i18n.t(
label ?? "Common.form.validationError.defaultFieldName"
);
return i18n.t("Common.form.validationError.required", {
label: fieldLabel,
});
},
},
string: {
max: ({ max, label }) => {
const fieldLabel = i18n.t(
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
(label as unknown as TemplateStringsArray) ??
"Common.form.validationError.defaultFieldName"
);
return i18n.t("Common.form.validationError.string.tooLong", {
max,
label: fieldLabel,
});
},
min: ({ min, label }) => {
const fieldLabel = i18n.t(
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
(label as unknown as TemplateStringsArray) ??
"Common.form.validationError.defaultFieldName"
);
return i18n.t("Common.form.validationError.string.tooShort", {
min,
label: fieldLabel,
});
},
email: i18n.t("Common.form.validationError.email.invalidFormat"),
},
number: {
positive: ({ label }) => {
const fieldLabel = i18n.t(
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
(label as unknown as TemplateStringsArray) ??
"Common.form.validationError.defaultFieldName"
);
return i18n.t("Common.form.validationError.numberic.positiveNumber", {
label: fieldLabel,
});
},
},
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment