Exploring the power of Lingui and yup validation within the NextJS framework

I'm using react-hook-form, yup in NextJS for form validation. I also implemented Lingui for internationalization by following this documentation. How can I set up internationalization in the yup validator that is supported by Lingui?

The issue I am encountering is that after changing the language, the errors from the yup validator remain in English.

// src/validation/auth.js

import * as yup from 'yup';
import { t } from '@lingui/macro';

export const signupEmailSchema = yup.object({
  email: yup
    .string()
    .email(
      t({
        id: 'email-valid-validation',
        message: 'Must be a valid email',
      })
    )
    .required(
      t({
        id: 'email-required-validation',
        message: 'Email is a required field',
      })
    ),
});
// pages/auth.js


export const Auth = () => {

 const {
    handleSubmit,
    control,
    formState: { errors },
  } = useForm({ resolver: yupResolver(signupEmailSchema) });
}

    <Controller
       name='email'
       control={control}
       render={({ field }) => (
                 <Input
                   placeholder='<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="452f2a2d2b212a20052228242c296b262a28">[email protected]</a>'
                      {...field}
                      ref={null}
                    />
              )}
     />
                {errors.email && (
                  <DangerText>
                    // need to display translated errors here
                  </DangerText>
                )}
}

Thank you.

Answer №1

To implement a Lazy Message pattern, refer to the documentation here

Below is an example of code incorporating this pattern:

// src/validation/auth.js

import * as yup from 'yup';
import { msg } from '@lingui/macro';

export const signupEmailSchema = yup.object({
  email: yup
    .string()
    .email(
      msg({
        id: 'email-valid-validation',
        message: 'Must be a valid email',
      }).id
    )
    .required(
      msg({
        id: 'email-required-validation',
        message: 'Email is a required field',
      }).id
    ),
});
// pages/auth.js
import { Trans } from '@lingui/react';


export const Auth = () => {
 const { _ } = useLingui();

 const {
    handleSubmit,
    control,
    formState: { errors },
  } = useForm({ resolver: yupResolver(signupEmailSchema) });
}

    <Controller
       name='email'
       control={control}
       render={({ field }) => (
                 <Input
                   placeholder='<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aac0c5c2c4cec5cfeacdc7cbc3c684c9c5c7">[email protected]</a>'
                      {...field}
                      ref={null}
                    />
              )}
     />
                {errors.email && (
                  <DangerText>
                    <Trans id={errors.email}>
                  </DangerText>
                )}
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Toggle button visibility on ng-repeat item click

Hello everyone, I'm encountering an issue with displaying and hiding buttons in ng-repeat. <div class="row" ng-repeat="item in items"> <button type="button" ng-click="add()">+</button> <button type="button" ng-click="remo ...

Every checkbox on the Angular 6 platform has been chosen

In my model class named processAnexOne.ts, I have the following structure: export class ProcessAnexOne { documentList: string; } Within the component class, I have initialized an instance as follows: export class ProcessAnexOneComponent implements O ...

Error message received from Express middleware: "Unable to modify headers after they have been sent."

I have created middleware for my Node Express app to perform the following tasks: Checking all incoming requests to determine if they are from a bot Allowing requests for raw resources to proceed Serving an HTML snapshot if the request is from a bot How ...

Leveraging the power of ajax to securely save information in a database with the web2py framework

Struggling with a major issue here. I have set up the following tables db.define_table('post', Field('user_email', default=auth.user.email if auth.user_id else None), Field('title', 'strin ...

The animation in threejs using lerp and camera transitions lacks fluidity

Why does linear interpolation pose a problem? When calling zoomCamera() inside an update() function that is being animated, there is a smooth lerp effect. However, when called within the onObjectsClick() function, the lerp is sharp. function onObjectsCl ...

Tips for retrieving the count from HTML using JavaScript:

I need to determine the count of list items in an unordered list within dir-pagination-controls. How can I achieve this using JavaScript? <dir-pagination-controls min-size="1" direction-links="true" boundary-links="true" class="pull-right ng-isolate- ...

What is the best way to transfer the array from my function and have it returned?

I've been struggling to successfully pass my array to an external function. Can anyone help me with this? You can find the code that I'm working on in jsbin: https://jsbin.com/kugesozawi/edit?js,console,output. The expected result should be passe ...

Encountering a problem with Nginx and WordPress where the admin-ajax.php is causing an issue when returning an AJAX result, leading to an error of Un

Currently, the issue is that everything runs smoothly on my Apache server, but when I switch to Nginx, an error is triggered with Uncaught SyntaxError: Unexpected token < Below is the function extracted from Functions.php function searchranges() { ...

How to use JavaScript to loop through and parse JSON data from Google Maps API

Hey there, I'm a beginner in javascript and I need some help. I am trying to figure out the best way to access a json object called "js" so that I can display different content for each marker on a map. Right now, all my markers are showing the same k ...

What is the best method for installing a package specified as a peerDependency?

I'm in the process of creating a library and I'm looking to figure out how to specify and install a dependency under peerDependencies. I couldn't find any information about this in the npm documentation when using the command npm install: ...

What is the best way to utilize Enquire.js for dynamically adding and removing CSS classes?

I'm looking to dynamically add and remove a css class based on a media query using Enquire.js but I could use some guidance on utilizing the functions properly. Here's what I envision in pseudo code: if (screens max-width > 480px){ #thumb.r ...

Iterate over rows in a b-table component in Vue

In the context of Vue bootstrap, a b-table consists of a list with an unknown number of rows. The requirement is to display a remove button only if the email in the row matches that of the currently logged-in user. This functionality currently works for a ...

Is there a way to prevent tinymce from automatically inserting <!DOCTYPE html><html><head></head><body> before all my content?

I have integrated TinyMCE as the editor for one of my database fields. The issue I am encountering is that when I input the text "abc" into the editor, it gets saved in the database surrounded by unnecessary HTML elements. This is the structure currently s ...

What could be causing the form DOM object values to not update in this specific instance?

I'm currently using JavaScript to create a password checksum by utilizing the SubtleCrypto.digest() function. This function produces the result as a promise object, which is then fed into an inline function to convert the outcome to a text representat ...

Exploring nested components traversal in React

In my project, I have created a product component that displays the products' name, price, and description. const Product = (props) =>{ return( <div> <p>Price: {props.price} </p> <p>Name: ...

How can you automate the execution of unit tests in Angular before pushing changes to Git?

There have been instances in Angular projects where the unit tests are triggered every time a build is carried out, as well as when running the git push command. In case any tests fail during either of these commands, the process halts until all unit tes ...

Press the button to automatically scroll to a designated div section

One of the challenges I'm facing involves a fixed menu and content box (div) on a webpage. Whenever I click on the menu, the content box should scroll to a specific div. Initially, everything was working fine. Here is a sample of it in action: http ...

Exploring the dynamics of Kendo UI's MVVM approach using J

Is there a way to make an ajax call in Kendo without involving the grid? I am new to Kendo and struggling to populate a span element with data fetched from one of my controller methods. The data is present as I can see it in the alert message, but it' ...

Utilizing React: passing a Component as a prop and enhancing it with additional properties

My question involves a versatile component setup like the one below const Img = ({ component }) => { const image_ref = useRef() return ( <> {component ref={image_ref} } </> ) } I am exploring ways to use this compo ...

Error message displayed when attempting to send emails through an HTML form obtained from a complimentary template site

Currently, I am in the process of learning to code basic websites but I'm facing some challenges with getting the contact form to function properly. I decided to work with a free template that can be found at this link: and uploaded it to a shared ho ...