【问题标题】:Setting Vuelidate custom error messages for built-in validators globally全局为内置验证器设置 Vuelidate 自定义错误消息
【发布时间】:2023-01-05 22:13:30
【问题描述】:

我在 Vue 3 中使用最新版本的 Vuelidate。有没有办法全局设置内置验证器的错误消息?我在文档中看到这个部分,它说在帮助对象上使用 withMessage 函数,如下所示:

import { required, helpers } from '@vuelidate/validators'

const validations = {
  name: {
    required: helpers.withMessage('This field cannot be empty', required)
  }
}

但这看起来需要在我们每次构建规则对象时进行设置。

【问题讨论】:

    标签: vue.js vuejs3 vuelidate


    【解决方案1】:

    您可以为 vuelidate 验证器创建带有包装器的文件,并在您的应用程序中使用它们。

    validators.js
    
    import { helpers, minLength, required } from '@vuelidate/validators';
    
    export const required$ = helpers.withMessage('This field cannot be empty', required)
    
    export const phoneMinLength$ = (min: number) => helpers.withMessage(
      ({ $params}) => `Phone number should contain ${$params.min} digits.`, minLength(min)
    )
    

    然后在你的应用程序中:

    import { required$, phoneMinLength$ } from './validators'
    
    ...
    validations() {
        return {
          form: {
            phone: {
              minLength: phoneMinLength$(9),
              required$,
            }
          }
        }
      },
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-26
      • 2018-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多