Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the Vee-Validate default error messages?

Using Vue.js and Vee-Validate, how can I change the default error messages?

Vee-Validate Example Demos

Out of the box, for the required message, it will display, "The <fieldname> field is required." But I just want all fields that are required to display "Required" instead. I know I can override individual fields but I just want to globally override any field that displays a required error to display "Required".

like image 217
RichC Avatar asked Jun 21 '18 16:06

RichC


2 Answers

Have a look at Field-specific Custom Messages in the official documentation.

You basically have to provide a custom dict for each language you want to override.

like image 87
chrisg86 Avatar answered Sep 28 '22 11:09

chrisg86


I have found an interesting gist, in fact you just have to override the dictionary. It seems so easy once done...

Interesting gist : https://gist.github.com/ramadimasatria/1819d4da13afb2ec3c2505f88bb760af

Setup:

  1. create a js file with your custom messages and a copy-paste of formatFileSize function since you cannot import it from vee-validate.

In my project, in standard-messages/messages.fr.js (copied from fr.js found at https://github.com/baianat/vee-validate/tree/4738e09c5397a951b9b986a4ce23e248bedcd295/locale):

const formatFileSize = size => {
  const units = ['Byte', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  const threshold = 1024
  size = Number(size) * threshold
  const i = size === 0 ? 0 : Math.floor(Math.log(size) / Math.log(threshold))
  return `${(size / Math.pow(threshold, i)).toFixed(2) * 1} ${units[i]}`
}

export default {
  _default: field => `${field} n'est pas valide.`,
  [...]
}
  1. Now in your validator's config, your custom messages will override default messages:

My validation/index.js:

import Vue from 'vue'
import VeeValidate from 'vee-validate'
import { messages as frOriginalMessages } from 'vee-validate/dist/locale/fr'
import { messages as nlOriginalMessages } from 'vee-validate/dist/locale/nl'
import { messages as deOriginalMessages } from 'vee-validate/dist/locale/de'
import frAttributes from './attributes/attributes.fr.json'
import nlAttributes from './attributes/attributes.nl.json'
import deAttributes from './attributes/attributes.de.json'
import validators from './validators'
import frCustomStandardMessages from './standard-messages/messages.fr.js'

export default {
  configure(currentLocale) {
    Vue.use(VeeValidate, {
      inject: false,
      locale: currentLocale,
      dictionary: {
        fr: { messages: { ...frOriginalMessages, ...frCustomStandardMessages }, 
attributes: frAttributes },
        nl: { messages: { ...nlOriginalMessages}, attributes: 
nlAttributes },
        de: { messages: { ...deOriginalMessages}, attributes: 
deAttributes }
      }
    })
like image 37
barbara.post Avatar answered Sep 28 '22 09:09

barbara.post