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.