user762579
user762579

Reputation:

Vue.js vee-validate custom dictionary setup

Currently, I am handling validation messages localization ( 3 languages) with vue-validate in each form component ( contactForm, registrationForm, ...)

i.e. for the contact form

ContactForm.vue

<script>
...
import English from 'vee-validate/dist/locale/en'
import French from 'vee-validate/dist/locale/fr'
import Portuguese from 'vee-validate/dist/locale/pt_BR'
...
import { Validator } from 'vee-validate'
...

// LOCALIZATION
const dict = {
  en: { custom: { honorificPrefix: { mrs: 'Mrs', mr: 'Mr' } } },
  br: { custom: { honorificPrefix: { mrs: 'Sra', mr: 'Sr' } } },
  fr: { custom: { honorificPrefix: { mrs: 'Mme', mr: 'Mr' } } }
}
Validator.localize('en', dict.en)
Validator.localize('br', dict.br)
Validator.localize('fr', dict.fr)

export default {
  name: 'contactForm',
  $_veeValidate: { validator: 'new' },
  data () {
    return {
    ...
    }
  },
  computed: {
    ...mapGetters(['language']),
    ...
  },
  methods: {
    ...
    submit: function () {
      ...
    },
    clear: function () {
     ...
    }
  },
  mounted () {
    this.$validator.localize('en', {
      messages: English.messages,
      attributes: {
        email: 'Email Address',
        givenName: 'First Nama',
        familyName: 'Name',
        messageContent: 'Message'
        //  other custom attributes
      },
      custom: {
        message: () => 'Message cannot be empty',
        select: 'Select field is required',
        correct_all: 'Please correct all errors in your form',
        error: 'Error',
        axiosPostError: 'Oops! An error occured and your message could not be sent.',
        success: 'Thanks',
        contactMsgSent: 'Your message has been successfully sent. We\'ll be in touch soon.'
      }
    })
    this.$validator.localize('fr', {
      messages: French.messages,
      attributes: {
        email: 'Adresse courriel',
        name: 'Nom',
        messageContent: 'Message'
        // autres attributs spécifiques
      },
      custom: {
        message: () => 'Vous n\'avez pas fourni de message',
        select: 'Vous devez sélectionner une option',
        correct_all: 'Veuillez corriger toutes les erreurs dans votre formulaire',
        error: 'Erreur',
        axiosPostError: 'Oops! Une erreur est survenue et votre message n\'a pas pu être envoyé',
        success: 'Merci',
        contactMsgSent: 'Votre message a été envoyé avec succès. Nous entrerons bientôt en contact avec vous.'
      }
    })
    this.$validator.localize('br', {
      messages: Portuguese.messages,
      attributes: {
        email: 'Endereço de e-mail',
        name: 'Nome',
        messageContent: 'Messagem'
        // outros atributos personalizados
      },
      custom: {
        message: () => 'Messagem cnão pode estar vazio',
        select: 'Selecione campo é obrigatório',
        correct_all: 'Por favor, corrija todos os erros em seu formulário',
        error: 'Erro',
        axiosPostError: 'Opa! Ocorreu um erro e sua mensagem não pôde ser enviada.',
        success: 'Obrigado',
        contactMsgSent: 'Sua mensagem foi enviada com sucesso. Nós entraremos em contato em breve.'
      }
    })
    // start with current locale locale.
    this.$validator.localize(this.language)
  }
}
</script>

As I have to repeat the same setup ( adding other custom attributes and messages ) for the other forms, I wonder if it should be better to move all that stuff into a shared js file and require it in each form? I guess it should be better to centralize the dictionary set up, but I am not sure of it .. and I am not sure to do it correctly

then I will have something like this :

ContactForm.vue (changed)

<script>
...

import appValidationDictionarySetup from 'appValidationDictionary.js'

export default {
  name: 'contactForm',
  $_veeValidate: { validator: 'new' },
  data () {
    return {
    ...
    }
  },
  computed: {
    ...mapGetters(['language']),
    ...
  },
  methods: {
    ...
    submit: function () {
      ...
    },
    clear: function () {
     ...
    }
  },
  mounted () {
     // => should perform the dictionary setup
     appValidationDictionarySetup(this.$validator)

    // start with current locale locale.
    this.$validator.localize(this.language)
  }
}
</script>

and a shared js file appValidationDictionary.js

appValidationDictionary.js

import { Validator } from 'vee-validate'


// LOCALIZATION
const dict = {
  en: { custom: { honorificPrefix: { mrs: 'Mrs', mr: 'Mr' } } },
  br: { custom: { honorificPrefix: { mrs: 'Sra', mr: 'Sr' } } },
  fr: { custom: { honorificPrefix: { mrs: 'Mme', mr: 'Mr' } } }
}

Validator.localize('en', dict.en)
Validator.localize('br', dict.br)
Validator.localize('fr', dict.fr)

var appValidationDictionarySetup = function (validator) { {
validator.localize('en', {
  messages: English.messages,
  attributes: {
    email: 'Email Address',
    givenName: 'First Nama',
    familyName: 'Name',
    messageContent: 'Message'
    //  other custom attributes
  },
  custom: {
    message: () => 'Message cannot be empty',
    select: 'Select field is required',
    correct_all: 'Please correct all errors in your form',
    error: 'Error',
    axiosPostError: 'Oops! An error occured and your message could not be sent.',
    success: 'Thanks',
    contactMsgSent: 'Your message has been successfully sent. We\'ll be in touch soon.'
    //  other custom messages
  }
})
validator.localize('fr', {
  messages: French.messages,
  attributes: {
    email: 'Adresse courriel',
    name: 'Nom',
    messageContent: 'Message'
    // autres attributs spécifiques
  },
  custom: {
    message: () => 'Vous n\'avez pas fourni de message',
    select: 'Vous devez sélectionner une option',
    correct_all: 'Veuillez corriger toutes les erreurs dans votre formulaire',
    error: 'Erreur',
    axiosPostError: 'Oops! Une erreur est survenue et votre message n\'a pas pu être envoyé',
    success: 'Merci',
    contactMsgSent: 'Votre message a été envoyé avec succès. Nous entrerons bientôt en contact avec vous.'
    //  other custom messages
  }
})
validator.localize('br', {
  messages: Portuguese.messages,
  attributes: {
    email: 'Endereço de e-mail',
    name: 'Nome',
    messageContent: 'Messagem'
    // outros atributos personalizados
  },
  custom: {
    message: () => 'Messagem cnão pode estar vazio',
    select: 'Selecione campo é obrigatório',
    correct_all: 'Por favor, corrija todos os erros em seu formulário',
    error: 'Erro',
    axiosPostError: 'Opa! Ocorreu um erro e sua mensagem não pôde ser enviada.',
    success: 'Obrigado',
    contactMsgSent: 'Sua mensagem foi enviada com sucesso. Nós entraremos em contato em breve.'
    //  other custom messages
  }
})
}
export { appValidationDictionarySetup }

If possible, how should I write correctly the js file and how should I request it correctly from my components?

thanks for feedback

Upvotes: 2

Views: 3052

Answers (1)

user762579
user762579

Reputation:

SOLVED

In my forms I have to add

import appValidationDictionarySetup from '@/locales/appValidationDictionary'

and in the mounted() hook

 mounted () {
appValidationDictionarySetup(this.$validator)
// start with current locale locale.
this.$validator.localize(this.language)

}

In the appValidationDictionary.js , I can move all the stuff and export the function

import { Validator } from 'vee-validate'

import English from 'vee-validate/dist/locale/en'
import French from 'vee-validate/dist/locale/fr'
import Portuguese from 'vee-validate/dist/locale/pt_BR'

// LOCALIZATION
const dict = {
  en: { custom: { honorificPrefix: { mrs: 'Mrs', mr: 'Mr' } } },
  br: { custom: { honorificPrefix: { mrs: 'Sra', mr: 'Sr' } } },
  fr: { custom: { honorificPrefix: { mrs: 'Mme', mr: 'Mr' } } }
}

Validator.localize('en', dict.en)
Validator.localize('br', dict.br)
Validator.localize('fr', dict.fr)

export default function appValidationDictionarySetup (validator) {
  validator.localize('en', {
    messages: English.messages,
    attributes: {
      email: 'Email Address',
      givenName: 'First Nama',
      familyName: 'Name',
      messageContent: 'Message'
      //  other custom attributes
    },
    custom: {
      message: () => 'Message cannot be empty',
      select: 'Select field is required',
      correct_all: 'Please correct all errors in your form',
      error: 'Error',
      axiosPostError: 'Oops! An error occured and your message could not be sent.',
      success: 'Thanks',
      contactMsgSent: 'Your message has been successfully sent. We\'ll be in touch soon.'
      //  other custom messages
    }
  })
  validator.localize('fr', {
    messages: French.messages,
    attributes: {
      email: 'Adresse courriel',
      name: 'Nom',
      messageContent: 'Message'
      // autres attributs spécifiques
    },
    custom: {
      message: () => 'Vous n\'avez pas fourni de message',
      select: 'Vous devez sélectionner une option',
      correct_all: 'Veuillez corriger toutes les erreurs dans votre formulaire',
      error: 'Erreur',
      axiosPostError: 'Oops! Une erreur est survenue et votre message n\'a pas pu être envoyé',
      success: 'Merci',
      contactMsgSent: 'Votre message a été envoyé avec succès. Nous entrerons bientôt en contact avec vous.'
      //  other custom messages
    }
  })
  validator.localize('br', {
    messages: Portuguese.messages,
    attributes: {
      email: 'Endereço de e-mail',
      name: 'Nome',
      messageContent: 'Messagem'
      // outros atributos personalizados
    },
    custom: {
      message: () => 'Messagem cnão pode estar vazio',
      select: 'Selecione campo é obrigatório',
      correct_all: 'Por favor, corrija todos os erros em seu formulário',
      error: 'Erro',
      axiosPostError: 'Opa! Ocorreu um erro e sua mensagem não pôde ser enviada.',
      success: 'Obrigado',
      contactMsgSent: 'Sua mensagem foi enviada com sucesso. Nós entraremos em contato em breve.'
      //  other custom messages
    }
  })
}

Upvotes: 1

Related Questions