Issues arising from Vue, Yup, and i18n integration for translations

I am currently developing a Vue.js App (using Vite) where I have integrated Vee-validate with Yup for form validation, as well as i18n for message translation. However, I am experiencing an issue where the custom errors defined in the schema do not dynamically update when the user changes the locale using $i18n.locale='xx'.

Here is the schema code snippet:

import { useI18n } from "vue-i18n"

const {t} = useI18n()

const schema = yup.object().shape({
  username: yup
    .string()
    .required(t("field_required"))
    .email(t("field_error_email")),
  password: yup.string().required(t("field_required"))
})

It is worth mentioning that messages displayed directly in the template using $t("message") function are functioning properly.

Below are the versions of the dependencies used:

"dependencies": {
    "vee-validate": "^4.5.11",
    "vue": "^3.2.33",
    "vue-i18n": "^9.1.9",
    "yup": "^0.32.11"
}

Answer №1

t("field_required") is used as a static string value when setting up the component, making it non-reactive. To make it reactive, the message should be evaluated at the time it is actually needed, such as during schema validation. Ideally, the required and other schema methods should accept a function to lazily evaluate the message for this purpose, which they currently do.

Instead of:

const schema = yup.object().shape({
  username: yup
    .string()
    .required(() => t("field_required"))
    ...

Answer №2

When working with a watcher, the structure might resemble the following:

   watch(i18n.global.locale, () => {
     if (<TOBECONFIRMED>.meta.value.touched) <TOBECONFIRMED>.validate();
   });

meta and validate are both attributes that can be extracted from useForm() if vee-validate is utilized.

Answer №3

If you want to pass your translated string, you can do it like this:

import * as yup from 'yup';

const schema = yup.object({
    name: yup.string().required(),
    email: yup.string('Must be string')
                .email('Must be email')
                .required('Required input'),
    password: yup.string().required().min(6),
});

https://i.sstatic.net/1TXsL.png

Make sure to also refer to this link: https://www.npmjs.com/package/yup#validation-tests

Answer №4

I managed to figure it out, but I am receiving a message with an extra set of quotation marks. For instance, we expect to see (The Password field is required) but we are seeing ("The Password field is required").

Below is the code snippet I am working with.

import ValidateForm from '@/composable/validation/schemas/ValidateForm';
import { useLocalization } from 'vue-i18n';

const mRequiredField = (fieldName: string) => {
  const { t } = useLocalization();
  return computed<string>(() => {
    return t('validation.required', { field: t(`fields.${fieldName}`) });
  });
};

const { errors, values, handleSubmit, resetForm } = ValidateForm(
  yup.object({
    password: yup.string().required(mRequiredField('password')),
  }),
);

view image details here

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

Ways to stop your Browser from Caching

Developing a Facebook app has been my recent project. One thing that really bothers me is the random occurrences where changes I make to my CSS style sheet or when adding a new Javascript function do not reflect in the browser. This can be very frustrating ...

Using Angular to sort arrays based on the values in a separate array

I have a unique setup where there is a table containing select options in each row. The value of the select option changes based on the 'dataType' specified for that particular row. Here is an example of my Table Array: { 'name':' ...

Is there a way to speed up the loading time of React in the browser?

My experience with using React in the browser has been positive, but I'm facing a speed issue. The initial loading time is quite lengthy as it compiles. I am looking for a way to use React/JSX directly in the browser and have it compile instantly wit ...

I'm running into some issues with flexbox and I'm in need of some assistance to find

I positioned two divs next to one another, but instead of each taking up 100vw, they are both sharing 50% of the available space. Is there a solution for this issue? Thank you. Page Image import type { AppProps } from "next/app"; import "./global.cs ...

The ideal structure for a Vue app

As a newcomer to Vue, I've been exploring different guidelines on how to use it effectively. In one resource here, the project was structured with separate directories for assets, components, routes, services, and views within a 'src' direct ...

Should you consider using the Singleton pattern in Node.js applications?

After stumbling upon this specific piece discussing the creation of a singleton in Node.js, it got me thinking. The require functionality according to the official documentation states that: Modules are cached after the first time they are loaded. Multi ...

Removing vacant rows from a table using Jquery in asp.net mvc

In my partial view, I am using BeginCollectionItem to manage the code. <tr> @using (Html.BeginCollectionItem("QuoteLines")) { <td> @Html.HiddenFor(m => m.QuoteID) @Html.HiddenFor(m => m.QuoteLineID) </td> ...

Tips for applying a class to an element depending on data stored in Local Storage using JQuery

I am currently working on a TODO list project with functions to save and delete records already in place. However, I am facing challenges with the functions for marking items as important and done. One method I use is to retrieve saved items from Local St ...

How can we effectively manage error responses and retry a failed call in NodeJS without getting tangled in callback hell?

I am in search of an effective approach to handle the given situation. I am curious if employing promises would be a helpful solution? Situation Overview: When a call retrieves a callback, and this callback receives an error object as a parameter. My obj ...

JavaScript having trouble parsing JSON, despite Chrome console being able to parse it flawlessly

I've hit a roadblock while attempting to retrieve coordinates from a database for the Google Maps API in order to create a polygon. First, I fetch my data from the database using Laravel Framework: MapController - public function getallmapcoords(re ...

The search function for selecting plugins is not functioning properly when additional options are added

Is there a way to use select options with search functionality, but the options are appended? I've tried using plugins like tom-select, selectize, and chosen but none of them seem to work with the appended options. Can anyone provide assistance on how ...

Obtaining the innerHTML value using JavaScript in an Asp.net Core 5 View

Apologies for any inaccuracies in my English writing. In the Asp.Net Core project view, I am trying to use JavaScript to capture multiple Span tags within innerHTML represented by a loop and display their sum in another tag. However, I am only able to ret ...

Insert a new class within the container div

I am looking to insert a 'disabled' class within a parent div named 'anchorxx' https://i.sstatic.net/3KRMQ.png The disabled class div can be located anywhere within the anchorXX divs Is it achievable using jquery? I am unsure how to ...

Approximating Values with JavaScript in Selenium

Hi there! I've been exploring selenium IDE and encountered an issue related to asserting an approximate value. My challenge is to validate a numeric value within an element identified by its id, where the value is in numerical format with commas separ ...

What is the process for combining multiple Vue components into a cohesive npm package?

My project manager at work tasked me with creating a single npm package for all the global components in our Vue project. This package should be easily importable and usable by everyone working on the project, similar to how Vuetify is imported from the no ...

Tips for retrieving the text enclosed within a <span> tag using jQuery

I am new to jQuery and came across this code online for a questionnaire. I want to save the selected options but I am not sure how to do it. " $.fn.jRadio = function (settings)" What is the purpose of this setting? " var options = $.extend(_de ...

Speed up the opening and closing of a div element on mouse hover

Looking to create a smooth delay for opening and closing a div when mouse hover. Here is the code I have: function show_panel1() { document.getElementById('hoverpanel1').style.display="block"; } function hide_panel1() { document.getElementByI ...

Discover the art of utilizing two distinct binding strings, wherein upon the selection of either, the alternate binding string shall automatically be

Having to use two different bindingstrings is a requirement due to a tool used for creating PDFs. My objective is to have the corresponding bindingstring turn "Off" when a user clicks on either the Yes or No button, and have the clicked button turn to "Yes ...

Selenium and Python encountered an ElementNotInteractableException, indicating that the element was not interactable when inserting a value

My current challenge involves inserting a value into a text box on a web page. The issue I'm facing is that the text box is located at the bottom of the page and seems to be unlocatable by the code initially. Upon inspecting it twice in Chrome, I real ...

How can I make the row color of a jQuery datatable change when the row is selected?

One of my challenges involves implementing a jquery dataTable (view here) where each row contains a checkbox. I want the row's color to change when the checkbox is checked. This is the approach I attempted: <table id="tabellaOrdinaFarmaci" class=" ...