【问题标题】:How to change the Vee-Validate default error messages?如何更改 Vee-Validate 默认错误消息?
【发布时间】:2018-12-01 01:56:05
【问题描述】:

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

Vee-Validate Example Demos

开箱即用,对于必需的消息,它将显示“fieldname> 字段是必需的。”但我只希望所有需要显示“必填”的字段。我知道我可以覆盖单个字段,但我只想全局覆盖任何显示必需错误以显示“必需”的字段。

【问题讨论】:

    标签: javascript vue.js vee-validate


    【解决方案1】:

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

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

    【讨论】:

    • 您好,martijn,我有一个名为 tr.js 的自定义字典,用于验证所有土耳其语消息,但我想知道如何在我的 Vue 项目中将它们用作默认值。你能帮忙吗?
    【解决方案2】:

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

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

    设置:

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

    在我的项目中,在standard-messages/messages.fr.js(从https://github.com/baianat/vee-validate/tree/4738e09c5397a951b9b986a4ce23e248bedcd295/locale找到的fr.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]}`
    }
    
    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 }
          }
        })
    

    【讨论】:

    • 感谢您抽出宝贵时间发布此内容。这是比公认的答案更好的解决方案。
    【解决方案3】:

    @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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-04
      • 2017-03-09
      • 1970-01-01
      • 2019-01-06
      • 1970-01-01
      • 1970-01-01
      • 2011-10-17
      • 2016-12-22
      相关资源
      最近更新 更多