Breaking News: Grepper is joining You.com. Read the official announcement!
Check it out

next-intl with zod

mrasadatik answered on March 18, 2024 Popularity 10/10 Helpfulness 1/10

Contents


More Related Answers


next-intl with zod

-1

Hey everyone!

I am not sure if my approach is entirely correct, but I figured out a way to manage next-intl translation values/message parameters with Zod for validation errors.

Let's start with the zod schema

Let's break down what we are passing or in what format we are passing the error message

In the message, we defined a specific format and separated the message key and translation values/message parameters with the | symbol.

In the implementation section, we extract key and translation values/message parameters by the following methods.

First, we store the error message in a variable

The above line of code checks if there's an error message associated with the username field. If there is, it splits the error message by | and stores the resulting parts in an array named dirtyErrorKeyAndTranslationValues. If there's no error, it creates an array with an empty string.

Then we extract the message key from the error message

The above code initializes a variable called refinedErrorKey as an empty string. It then checks if the first element of dirtyErrorKeyAndTranslationValues array (assumed to be a string) exists and has a length greater than zero. If true, it assigns the value of the first element of dirtyErrorKeyAndTranslationValues to refinedErrorKey.

Then we extract the translation values/message parameters from the error message

The above code initializes a variable named redinedTranslationValues as an empty object. It then checks if the second element of the dirtyErrorKeyAndTranslationValues array (expected to be a string) exists and has a length greater than zero. If true, it parses the second element of dirtyErrorKeyAndTranslationValues as JSON and assigns the resulting object to refinedTranslationValues.

After doing all the previous staff we can use it like

Here, if there's an error message associated with the username (errors.username), it invokes a translation function t() with parameters refinedErrorKey and refinedTranslationValues, unless refinedTranslationValues is empty. If there's no error message for the username, it renders an empty space.

Popularity 10/10 Helpfulness 1/10 Language javascript
Source: Grepper
Link to this answer
Share Copy Link
Contributed on Mar 18 2024
mrasadatik
0 Answers  Avg Quality 2/10


X

Continue with Google

By continuing, I agree that I have read and agree to Greppers's Terms of Service and Privacy Policy.
X
Grepper Account Login Required

Oops, You will need to install Grepper and log-in to perform this action.