如何更改 Vee-Validate 默认错误消息?

How to change the Vee-Validate default error messages?

使用 Vue.js 和 Vee-Validate,如何更改默认错误消息?

Vee-Validate Example Demos

开箱即用,对于所需的消息,它将显示,"The <fieldname> field is required." 但我只想显示所有需要的字段 "Required"。我知道我可以覆盖单个字段,但我只想全局覆盖任何显示必需错误以显示 "Required".

的字段

查看官方文档中的Field-specific Custom Messages

您基本上必须为要覆盖的每种语言提供自定义字典。

我发现了一个有趣的要点,事实上你只需要覆盖字典。完成后似乎很容易...

有趣的要点:https://gist.github.com/ramadimasatria/1819d4da13afb2ec3c2505f88bb760af

设置:

  1. 使用您的自定义消息和 formatFileSize 函数的复制粘贴创建一个 js 文件,因为您无法从 vee-validate 导入它。

在我的项目中,在 standard-messages/messages.fr.js(复制自 fr.js,发现于 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. 现在在您的验证器配置中,您的自定义消息将覆盖默认消息:

我的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 }
      }
    })

@barbara.post的回答基本上是正确的,但对我没有用。因为我们使用 vue-i18n 设置了 VeeValidate,所以我们的设置看起来有点不同。分享我们稍微修改过的解决方案来覆盖字典。

1。使用验证消息创建 JS 文件

创建 ./helper/vee-validate-standard-messages.de_DE.js:

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]}`
}

const isDefinedGlobally = () => {
    return typeof VeeValidate !== 'undefined'
}

const messages = {
    _default: (field) => `"${field}" ist ungültig.`,
    after: (field, [target]) => `"${field}" muss nach ${target} liegen.`,
    alpha_dash: (field) => `"${field}" darf alphanumerische Zeichen sowie Striche und Unterstriche enthalten.`,
    alpha_num: (field) => `"${field}" darf nur alphanumerische Zeichen enthalten.`,
    alpha: (field) => `"${field}" darf nur alphabetische Zeichen enthalten.`,
    before: (field, [target]) => `"${field}" muss vor ${target} liegen.`,
    between: (field, [min, max]) => `"${field}" muss zwischen ${min} und ${max} liegen.`,
    confirmed: (field, [confirmedField]) => `"${field}" passt nicht zum Inhalt von ${confirmedField}.`,
    date_between: (field, [min, max]) => `"${field}" muss zwischen ${min} und ${max} liegen.`,
    date_format: (field, [format]) => `"${field}" muss das Format ${format} haben.`,
    decimal: (field, [decimals = '*'] = []) => `"${field}" muss numerisch sein und darf ${decimals === '*' ? '' : decimals} Dezimalpunkte enthalten.`,
    digits: (field, [length]) => `"${field}" muss numerisch sein und exakt ${length} Ziffern enthalten.`,
    dimensions: (field, [width, height]) => `"${field}" muss ${width} x ${height} Bildpunkte groß sein.`,
    email: (field) => `"${field}" muss eine gültige E-Mail-Adresse sein.`,
    ext: (field) => `"${field}" muss eine gültige Datei sein.`,
    image: (field) => `"${field}" muss eine Grafik sein.`,
    included: (field) => `"${field}" muss ein gültiger Wert sein.`,
    ip: (field) => `"${field}" muss eine gültige IP-Adresse sein.`,
    max: (field, [length]) => `"${field}" darf nicht länger als ${length} Zeichen sein.`,
    mimes: (field) => `"${field}" muss einen gültigen Dateityp haben.`,
    min: (field, [length]) => `"${field}" muss mindestens ${length} Zeichen lang sein.`,
    excluded: (field) => `"${field}" muss ein gültiger Wert sein.`,
    numeric: (field) => `"${field}" darf nur numerische Zeichen enthalten.`,
    regex: (field) => `Das Format von "${field}" ist ungültig.`,
    required: (field) => `"${field}" ist ein Pflichtfeld.`,
    size: (field, [size]) => `"${field}" muss kleiner als ${formatFileSize(size)} sein.`,
    url: (field) => `"${field}" ist keine gültige URL.`,
};

const locale = {
    name: 'de_DE',
    messages,
    attributes: {}
};

if (isDefinedGlobally()) {
    VeeValidate.Validator.localize({ [locale.name]: locale });
}

export default locale;
2。配置 VeeValidate 消息字典

./i18n.js中:

import Vue from 'vue'
import VueI18n from 'vue-i18n'
import VeeValidate from 'vee-validate'
import validationMessagesEN from 'vee-validate/dist/locale/en'
// import validationMessagesDE from 'vee-validate/dist/locale/de'
import customvalidationMessagesDE from './helper/vee-validate-standard-messages.de_DE.js'

Vue.use(VueI18n)
const i18n = new VueI18n({
    locale: process.env.VUE_APP_I18N_LOCALE || 'de_DE',
    fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'de_DE',
    messages: loadLocaleMessages(),
    silentTranslationWarn: true
})
Vue.use(VeeValidate, {
    i18nRootKey: 'validations', // customize the root path for validation messages.
    i18n,
    dictionary: {
        en_EN: validationMessagesEN,
        de_DE: customvalidationMessagesDE
    }
})

function loadLocaleMessages () {
    const locales = require.context('./i18n', true, /([a-z]{2})+[_]+([A-Z]{2})+\.json$/)
    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 i18n