Search code examples
vue.jsvuejs3vuelidate

Setting Vuelidate custom error messages for built-in validators globally


I'm using the latest version of Vuelidate with Vue 3. Is there a way to globally set the error messages for the built-in validators? I see this section within the docs where it says to use the withMessage function on the helper object, like this:

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

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

But this looks like it needs to be set each time we build the rules object.


Solution

  • You can create file with wrappers for vuelidate validators and use them in your app.

    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)
    )
    

    then in your app:

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