Unable to set I18n locale for Vee-Validate in VueJS is ineffective

In my VueJS Application, I am implementing form validation using the Vee-Validate plugin. With multiple languages supported in my app, I have integrated I18n for localization. Each plugin is stored in separate files within the plugins folder and then imported and registered in the main.js. Here is an example from my Vee-Validate.js file:

import Vue from 'vue';
import VueI18n from 'vue-i18n';
import VeeValidate from 'vee-validate';
import enMessages from "./../locales/validation/en";
import urMessages from "./../locales/validation/ur";

Vue.use(VueI18n);

const i18n = new VueI18n();
i18n.locale = "en";

Vue.use(VeeValidate, {
  errorBagName: 'vErrors',
  i18nRootKey: 'validations',
  i18n,
  dictionary: {
    en: {
      messages: enMessages
    },
    ur: {
      messages: urMessages
    }
  }
});

Despite having a function to change the locale when clicking a button, it seems that this action does not affect the locale set in the above file.

Here is the code snippet for my change locale function:

changeLocale () {
  this.$i18n.locale == 'en' ? this.$i18n.locale = 'ur' : this.$i18n.locale = 'en'
  this.$vuetify.rtl = this.$i18n.locale === 'ur' ? true : false;
}

Answer №1

Indeed, I'm not suggesting that your setup is incorrect. Allow me to share mine, which is functioning perfectly.

1- vue.config.js

module.exports = {
  transpileDependencies: [
    'vuetify',
  ],

  pluginOptions: {
    i18n: {
      locale: 'en',
      fallbackLocale: 'en',
      localeDir: 'locales',
      enableInSFC: true,
    },
  },
};

2- i18n.ts

import Vue from 'vue';
import VueI18n, { LocaleMessages } from 'vue-i18n';

Vue.use(VueI18n);

function loadLocaleMessages(): LocaleMessages {
  const locales = require.context('./locales', true, /[A-Za-z0-9-_,\s]+\.json$/i);
  const messages: LocaleMessages = {};
  locales.keys().forEach((key) => {
    const matched = key.match(/([A-Za-z0-9-_]+)\./i);
    if (matched && matched.length > 1) {
      const locale = matched[1];
      messages[locale] = locales(key);
    }
  });
  return messages;
}

export default new VueI18n({
  locale: process.env.VUE_APP_I18N_LOCALE || 'en',
  fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'en',
  messages: loadLocaleMessages(),
});

3- main.ts

import Vue from 'vue';

import './registerServiceWorker';
import { sync } from 'vuex-router-sync';
import VueLodash from 'vue-lodash';
import Storage from 'vue-ls';
import vuetify from './plugins/vuetify';
import './utils/vee-validate';


// Components
import './components';

// Application imports
import App from './App.vue';
import router from '@/router';
import store from '@/store';
import i18n from './i18n';

// Sync store with router
sync(store, router);
const options = {
  name: 'ls', // name variable Vue.[ls] or this.[$ls],
  storage: 'local', // storage name session, local, memory
};
Vue.use(Storage, options);
Vue.config.productionTip = false;
Vue.use(VueLodash, { name: 'lodash' });
new Vue({
  router,
  store,
  vuetify,
  i18n,
  render: h => h(App),
}).$mount('#app');

4- src/plugins/vuetify.ts

import Vue from 'vue';
import Vuetify from 'vuetify/lib';


// import VueI18n from 'vue-i18n';
// import i18n from '@/i18n';
import en from '@/locales/en.json';
import jp from '@/locales/jp.json';


Vue.use(Vuetify);


export default new Vuetify({
  lang: {
    locales: { en, jp },
    current: 'jp',
  },
});

5- src/utils/vee-validate.js

/* eslint-disable no-underscore-dangle */
import { extend } from 'vee-validate';
import { required, email, confirmed } from 'vee-validate/dist/rules';
import i18n from '@/i18n';


extend('required', {
  ...required,
  message: (_, values) => i18n.t('GENERAL_VALIDATION_MESSAGES_REQUIRED', values),
});

extend('email', {
  ...email,
  message: (_, values) => i18n.t('LOGIN_FORM_EMAIL_VALID_MESSAGE', values),
});
extend('confirmed', {
  ...confirmed,
  message: (_, values) => i18n.t('CHANGE_PASSWORD_FORM_CONFIRMATION_VALID_MESSAGE', values),
});

6- Since I utilize vuex, here is a snippet from my language store

import Vue from 'vue';
import { localize } from 'vee-validate';
import Vuetify from 'vuetify/lib';
import i18n from '@/i18n';
import en from '@/locales/en.json';
import jp from '@/locales/jp.json';

...

const mutations = {
  SET_LANG(state, data) {
    state.lang = data;
    i18n.locale = data;
    localize(data, jp);
  },
  SET_LANG_ERROR() {
    window.$messageGlobal('Error switching languages');
  },
};

I hope you find this information helpful

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

Switching an :active class using ReactJS

Currently, I am working on creating an onboarding screen where the user is required to select three or more items. Once the user clicks on an item, a purple overlay should remain visible. For reference, this is what I have in mind: https://i.sstatic.net/ ...

The curly braces in AngularJS are failing to display the values on the HTML page

After trying various articles and solutions to different questions, I am still unable to resolve my issue. I am working on a blank ionic project and it is running smoothly in my browser using ionic serve without any errors. However, instead of displaying ...

Is it necessary to include Babel when integrating Webpack?

After reading an informative article, it is highlighted that Babel’s plugin-syntax-dynamic-import plays a crucial role in enabling lazy loading. Without this, the syntax const AppHome= () => import("@/components/AppHome"); will not be compiled by webp ...

Having a parameter that contains the characters '&' and '&' can potentially disrupt an AJAX call

Even though there is a similar question here: Parameter with '&' breaking $.ajax request, the solutions provided do not apply to my specific issue. This is because both the question and answers involve jQuery, which I am not familiar with. I ...

Testing a React component that uses useParams: A step-by-step guide

I've been working on creating a BBS App using TypeScript, React, React Router, and React Testing Library. However, I've encountered an issue where a component utilizing useParams is not passing a test. Interestingly, it seems to be working correc ...

Fundamental modeling using Node.js with Mongoose

Currently, I am facing a challenge with developing a node.js application. My goal is to create a model for a musical scale that includes a name and a set of associated notes: var mongoose = require('mongoose'); var Schema = mongoose.Schema; var ...

Determining when ng-repeat has completed in Angular JS

Is there a way to determine when ng-repeat has completed populating the values in the markup? Since I have numerous values, it may take some time for the rendering process. NG <ul > <li data-ng-repeat="item in values"> ...

The loop feature in Swiper.js seems to be malfunctioning and not functioning as

I'm currently in the process of setting up a carousel using swiper.js and here is my setup: { slidesPerView: 1, slidesPerColumn: 1, initialSlide: this.initialSlide, loop: true } As expected, I'm encountering an issue where dupl ...

Why isn't the close button in jQuery working on an Asp.net page?

My current project involves working with Asp.net and C#. I am facing an issue where I click on a button to display a message in a popup box, but when I try to close the popup by clicking the close button, it does not close. Here is the syntax for the aspx ...

Refresh the current page with jQuery Mobile when it is clicked

I have a multi page template in jQuery Mobile. How can I refresh the current page when clicking on a hyperlink or button? I am using JQM version 1.4.5 Despite trying the code suggested in how to refresh(reload) page when click button in jQuery Mobile, it ...

"Converting an HTML file to a Word file using PHP - a step-by-step

Help needed with converting an HTML file to MS Word using PHP code. Below is the code I am using: include("connection.php"); extract($_REQUEST); ob_start(); include("counties/$county_name/$file"); $html_content = ob_get_contents(); ob_end_clean(); header ...

Getting the response from Google Cloud Translate API using Node JS

Recently, I've been experimenting with the Google Cloud Translate API in NodeJS. While I am able to successfully console.log the value returned from a promise, I am facing challenges passing that value into an EJS template file. Whenever I try to disp ...

Covering a doughnut shape with a twisting spiral

I want to achieve a hula hoop covered in tape effect using three.js. The 3D model should look similar to the image below. https://i.sstatic.net/lj9cR.jpg I have been able to create the hoop in 3D space using TorusGeometry and pan around, but I am strugg ...

Validation of default values in contact forms

Obtained a free contact form online and hoping it works flawlessly, but struggling with validation for fields like "Full Name" in JS and PHP. Here is the HTML code: <input type="text" name="contactname" id="contactname" class="required" role="inpu ...

How to invoke a function from a different ng-app in AngularJS

I have 2 ng-app block on the same page. One is for listing items and the other one is for inserting them. I am trying to call the listing function after I finish inserting, but so far I haven't been successful in doing so. I have researched how to cal ...

What could be causing my Express API registration route to fail when attempting to POST?

Currently, I'm in the process of developing a compact authentication system for a practice project that I've undertaken. As part of this endeavor, I am sending POST requests via Postman to my Express server located at http://localhost:4000/api/re ...

The meaning gets blurred when using 'this' in a prototype method

Alright, so I am working on a node application that utilizes express. In this particular application, there's an express route set up like this: var MyObject = require('./myObject') , myObject = new MyObject(); app.post('/api/w ...

Discover the best method for retrieving or accessing data from an array using Angular

In my data processing task, I have two sets of information. The first set serves as the header data, providing the names of the columns to be displayed. The second set is the actual data source itself. My challenge lies in selecting only the data from th ...

What is the correct way to chain custom callback functions using .queue()?

I am currently grappling with the concept of chaining custom functions: My code snippet looks like this: show_loader(0, function() { open_box($target_open, event.value, '.wide-col', function() { hide_loader(function() { ...

Using multiple ng-controller directives with the "controller as x" syntax on a single element

What is the reason that Angular does not allow two ng-controller directives on a single element and What are some potential solutions for this issue - such as using custom directives or nesting HTML elements with a single ng-controller directive, among oth ...