skip to Main Content

i am using vee-validate v.2 and i want to localize error massages .
i have wrote a plugin like this

    import {configure} from 'vee-validate'
export default function ({app}){
    configure({
        defaultMessage:(field,values)=>{
            values._field_=app.i18n.t(`fields.${field}`)
            return app.i18n.t(`validation.${values._rule_}`,values)
        }
    })
}

and this is loacales/en.js

  validation: {
    required: "{_field_} can not be empty",
    min: "{_field_} may not be Less than {length} characters",
    confirmed: "{_field_} do not matches",
    email: "{_field_} is not valid"
  },
  fields: {
    email: 'Email',
    password: 'Password',
    userName: 'Username',
    
  },
  
}

and Also this is $i18n in nuxt config

 i18n: {
    seo: false,
    locales: [
      { code: 'en', iso: 'en-US', file: 'en.js' },
      { code: 'de', iso: 'de-GER', file: 'de.js' }
    ],
    lazy: true,
    langDir: 'locales/',
    baseUrl: process.env.BASE_URL,
    defaultLocale: 'de'
  },

BUT it doesnt work ,
and pages dont shows
and i get error like this
enter image description here
How can do i fixed it ?

2

Answers


  1. Let me explain my solution step by step :

    Step 1) Install the required packages:

    npm install nuxt-i18n --save
    npm install vee-validate --save
    
    package.json
    {
     "@nuxtjs/i18n": "^7.0.1",
     "vee-validate": "^3.4.12"
    }
    

    Step 2) Create a folder named /locales to the root of your project.

    Step 3) Create a file /locales/en.js for English

    import en from 'vee-validate/dist/locale/en'
    
    export default async (context, locale) => {
      return {
        validation: en.messages,
        email : "email",
      };
    }
    

    Step 4) Create a file /locales/tr.js for Second Language (Türkçe)

    import en from 'vee-validate/dist/locale/tr'
    
    export default async (context, locale) => {
      return {
        validation: tr.messages,
        email : "e-posta",
      };
    }
    

    Step 5) Create a i18n plugin file /plugins/i18n.js

    import {configure } from "vee-validate";
    
    export default function ({app}) {
        configure({
        defaultMessage: (field, values) => {
          return app.i18n.t(`validation.${values._rule_}`, values);
        }
      });
    }
    

    Step 6) Create a validation plugin file /plugins/validate.js

    import Vue from 'vue'
    
    import { ValidationProvider, ValidationObserver, extend} from 'vee-validate';
    import { required, email } from 'vee-validate/dist/rules';
    
    Vue.component('appValidationProvider', ValidationProvider);
    Vue.component("appValidationObserver", ValidationObserver);
    
    extend("required", required);
    extend("email", email);
    

    Note: I used ‘required’ and ’email’ rule in this example if you want to use more rules you can visit the guide page and add to this file.

    All rule list : https://vee-validate.logaretm.com/v2/guide/rules.html

    Step 7) nuxt.config -> plugin Configuration

      plugins: [
        '~/plugins/i18n.js',
        '~/plugins/validate.js',
      ],
    

    Step 8) nuxt.config -> i18n module Configuration

        modules: [
        ['nuxt-i18n', {
          baseUrl: 'https://yourdomain.com',
          lazy: true,
          loadLanguagesAsync: true,
          locales: [
            {
              name: 'English',
              code: 'en',
              iso: 'en-US',
              file: 'en.js'
            },
            {
              name: 'Türkçe',
              code: 'tr',
              iso: 'tr-TR',
              file: 'tr.js'
            },
          ],
          langDir: 'locales/',
          defaultLocale: 'en',
          vueI18n: {
             fallbackLocale: 'en'
          },
          strategy: 'prefix_and_default',
          detectBrowserLanguage: {
            useCookie: true,
            cookieKey: 'i18n_redirected',
            alwaysRedirect: false,
            fallbackLocale: 'en',
            redirectOn: 'root'
          },
          parsePages: false,
          pages: {
            'contact/index': {
              tr: '/iletisim',
              en: '/contact'
            }
          }
        }]
      ],
    

    Step 9) nuxt.config -> vee-validate configuration add this :

    build: {
        transpile: ['vee-validate/dist/rules',
                    'vee-validate/dist/locale/tr',
                    'vee-validate/dist/locale/en']
      },
    

    Usage -> page : contact/index.vue

    <template>
     <app-validation-observer v-slot="{ handleSubmit }">
       <form class="form" @submit.prevent="handleSubmit(onSubmit)">
    
          <app-validation-provider rules="required|email" v-slot="{ errors }">
              <input type="text" :name="$t('email')" v-model="formData.email">
              <span class="is-invalid">{{ errors[0]}}</span>
              <button>Test</button>
          </app-validation-provider>
    
        </form>
     </app-validation-observer>
    </template>
    <script>
    export default {
        name: "contact",
        data() {
          return {
            formData: {
              email: ''
            }
          }
        },
        methods: {
          onSubmit() {
            console.log('form posted :)');
          }
        }
      }
    </script>
    <style scoped>
      .is-invalid {
        color: red;
      }
    </style>
    
    Login or Signup to reply.
  2. in the file vee-validate.js

    import configure method

    import {
       configure
    } from 'vee-validate/dist/vee-validate.full.esm'
    

    then use it like

    export default ({ app: { i18n } }) => {
    
      configure({
        defaultMessage: (field, values) => {
          return i18n.t(`validation.${values._rule_}`, values);
        }
      });
    })
    

    and in i18n translations folder add for every language

    import en from 'vee-validate/dist/locale/en'
    
    export default {
        validation: en.messages,
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search