全局设置内置验证器的 Vuelidate 自定义错误消息

ken*_*in9 1 vue.js vuelidate vuejs3

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

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

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

但这看起来像是每次我们构建规则对象时都需要设置。

小智 8

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

验证器.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)
)
Run Code Online (Sandbox Code Playgroud)

然后在你的应用程序中:

import { required$, phoneMinLength$ } from './validators'

...
validations() {
    return {
      form: {
        phone: {
          minLength: phoneMinLength$(9),
          required$,
        }
      }
    }
  },
...
Run Code Online (Sandbox Code Playgroud)