Change vee-validate message in runtime

40 Views Asked by At

I'm trying to change my vee-validate messages in runtime

I have two files with languages: pt.json and en.json

I have an i18n.js file:

import Vue from 'vue'
import VueI18n from 'vue-i18n'

Vue.use(VueI18n)

function loadLocaleMessages () {
  const locales = require.context('./locales', true, /[A-Za-z0-9-_,\s]+\.json$/i)
  const messages = {}
  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 || 'pt',
  fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'pt',
  messages: loadLocaleMessages()
})

My validations.js file:

import { extend } from 'vee-validate';
import { required } from 'vee-validate/dist/rules'
import i18n from '@/i18n';

extend('required', {
    ...required,
    message:  '{_field_} ' + i18n.t('validations.mandatory'),
})

Inside main.js I call the two files:

(...)
import i18n from './i18n'
import './plugins/validations'
(...)

My default language is PT but I can change the language to EN and all the texts are updated but the error messages are not. Inside my validations.js, if I force the locale to change it works:

import { extend } from 'vee-validate';
import { required } from 'vee-validate/dist/rules'
import i18n from '@/i18n';

i18n.locale = 'en'

extend('required', {
    ...required,
    message:  '{_field_} ' + i18n.t('validations.mandatory'),
})

The thing is that I want to change this in runtime, when I change the language inside the component. I tried to add the localeChanged() and localize() function inside the component, before the language change but still not working.

import { localeChanged } from 'vee-validate';

(...)

this.$i18n.locale = 'ar'; // locale changed
localeChanged(); // notify vee-validate of localization changes

What am I missing if there's someone that can help?

enter image description here

0

There are 0 best solutions below