Skip to content
Advertisement

How to configure vee-validate globally in vue?

My question, is there a way we could create a one .js file and state all extend(s)? so we don’t need to extend each time we use the validator.

I just ask because my codes becomes lengthy each time I need a validator. I need to extend it first to be usable.


I’m currently using vue & vuetify with vee-validate. The below codes are working fine reference.

template

<ValidationObserver ref="observer" v-slot="{ validate, reset }">
    <ValidationProvider v-slot="{ errors }" name="Name" rules="required|max:10">
        <v-text-field v-model="user.name" :error-messages="errors" label="Name" type="text"></v-text-field>
    </ValidationProvider>
</ValidationObserver>

script

import { confirmed, required, email, max } from "vee-validate/dist/rules";
import { extend, ValidationObserver, ValidationProvider, setInteractionMode } from "vee-validate";

setInteractionMode("eager");

extend("required", {
  ...required,
  message: "{_field_} can not be empty",
});

extend("confirmed", {
  params: ["target"],
  validate(value, { target }) {
    return value === target;
  },
  message: "{_field_} does not match",
});

extend("max", {
  ...max,
  message: "{_field_} may not be greater than {length} characters",
});

extend("email", {
  ...email,
  message: "Email must be valid",
});

Advertisement

Answer

Yes, you can declare all your configuration in one file, then import that into your main.js. So, you’d have

// validationConfig.js

import { confirmed, required, email, max } from "vee-validate/dist/rules";

extend()
extend()
//etc

In main:

// main.js

import path/to/validationConfig
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement