Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

904
Visualizações
How to generate error messages with Zod in different Languages

I want to generate validation messages in different languages. I wanted to create my own middleware that adds a lang attribute to the request object. And after setting lang, I will validate my requests with Zod. I am not able to send the lang as another parameter to schema.parse() method. Here is the code :

ValidateResource

const validate =
    (schema: AnyZodObject) =>
        (req: Request, res: Response, next: NextFunction) => {
            try {
                schema.parse({
                    body: req.body,
                    query: req.query,
                    params: req.params,
                }, );
                next();
            } catch (e: any) {
                if(e instanceof  ZodError) return res.status(StatusCodes.BAD_REQUEST).send(e.flatten());
                return next()
            }
        };

CreateUserSchema



export const createUserSchema = z.object({

    body :  object({
        name : z.string({
            required_error : "Name is required"
        }),
        surname : z.string({
            required_error : "last name is required"
        }),
        password : z.string({
            required_error : "password is required"
        }),
        email : z.string({
            required_error: "Email is required"
        }).email({
            message : "Not a valid email"
        }),
        gender : z.enum([Gender.F,Gender.M]),
        profilePicture : z.string().url().default(config.get<string>("defaultProfilePictureURL")).optional(),
        phoneNumber : z.string({
            required_error : "Phone number is required for singing up"
        }),
        dateOfBirth : z.date().optional(),
    })
})

I have a getMessage method that simply returns an object of message list.


export function getMessage (lang : string) : messages {

    if(lang == "tr"){
        return messagesInTurkish
    }

    return messagesInEnglish
}

export interface messages {
    forbidden : string,
    internalServerError : string,

}

const messagesInTurkish : messages = {
    forbidden: "Yasak Kaynak",
    internalServerError: "Server Hatası"
}

const messagesInEnglish : messages = {
    forbidden: "Forbidden",
    internalServerError: "Internal Server Error"

I want to make CreateUserSchema as

const params = {
    params: object({
        _id: z.string({
            required_error:  getMessage(req.body.lang),
        }),
    }),
};

However, the request object is not carried here. How can I make it dynamic?

over 4 years ago · Santiago Trujillo
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda