Getting "invalid value" when trying to translate validation error messages in Express

1 week ago 15
ARTICLE AD BOX

I installed i18next packages in my Express project and enabled i18next.

middleware\localization.ts:

import i18next from "i18next"; import Backend from "i18next-fs-backend"; import { LanguageDetector } from "i18next-http-middleware"; i18next .use(Backend) .use(LanguageDetector) .init({ lng: "sr", ns: ["validation"], fallbackLng: "en", backend: { loadPath: `../lang/{lng}/{ns}.json` } });

I have a validation file lang/sr/validation.json.

I have multiple validation schema middleware for express-validator which have translated error messages. One of them is registerSchema, which is adde

d to registration view.

validation\authSchemas.ts:

import { checkSchema } from "express-validator"; import i18next from "i18next"; import moment from "moment"; // 3 input validation & sanitization export const registerSchema = checkSchema({ email: { notEmpty: { errorMessage: i18next.t("field.empty", { attr: i18next.t("attrs.email") }) }, isEmail: { errorMessage: i18next.t("email.email", { attr: i18next.t("attrs.email") }) } }, password1: { notEmpty: { errorMessage: i18next.t("field.empty", { attr: i18next.t("attrs.password1") }) } }, password2: { notEmpty: { errorMessage: i18next.t("field.empty", { attr: i18next.t("attrs.password2") }) }, custom: { errorMessage: i18next.t("password2.confirmed"), options: (value, { req }) => value === req.body.password1 } }, phone: { notEmpty: { errorMessage: i18next.t("field.empty", { attr: i18next.t("attrs.phone") }) }, matches: { errorMessage: i18next.t("phone.regex"), options: /\+381 \d{2} \d{6,7}/gm } }, firstName: { notEmpty: { errorMessage: i18next.t("field.empty", { attr: i18next.t("attrs.firstName") }) }, isAlpha: { errorMessage: i18next.t("field.alpha", { attr: i18next.t("attrs.firstName") }) } }, lastName: { notEmpty: { errorMessage: i18next.t("field.empty", { attr: i18next.t("attrs.lastName") }) }, isAlpha: { errorMessage: i18next.t("field.alpha", { attr: i18next.t("attrs.lastName") }) } }, birthDate: { notEmpty: { errorMessage: i18next.t("field.empty", { attr: i18next.t("attrs.birthDate") }) }, isDate: { errorMessage: i18next.t("field.date", { attr: i18next.t("attrs.birthDate") }) }, custom: { errorMessage: i18next.t("birthDate.adult"), options: (value) => { const age = moment().diff(new Date(value), "years"); return age >= 18; } } } });

routes\index.ts:

import { Router } from "express"; import controller from "../controllers/authController"; import { requireAuth } from "../middleware/auth"; import { limitAuth } from "../middleware/rateLimits"; import { loginSchema, registerSchema } from "../validation/authSchemas"; const router = Router(); // 3 input validation & sanitization router.post("/registracija", limitAuth, registerSchema, controller.register);

When I press the submit button, all of the validation messages are Invalid value.

Invalid value

How do I fix this?

Read Entire Article