5

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".

4

3 回答 3

4

在官方文档中查看特定于字段的自定义消息。

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

于 2018-06-21T17:12:54.270 回答
2

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

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

设置:

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

在我的项目中,在标准消息/消息

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. 现在在您的验证器配置中,您的自定义消息将覆盖默认消息:

我的验证/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 }
      }
    })
于 2018-11-12T12:27:04.890 回答
-1

@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
于 2022-01-11T08:17:24.437 回答