zernzern1993
zernzern1993

Reputation: 265

$validator undefined vee-validate NuxtJS

I have vee-validation setup and working on my NuxtJS project and validation is working well but I cant access the $validator and it is always undefined...

My plugin file:-

import { extend, ValidationObserver, ValidationProvider } from "vee-validate";
import * as VeeValidate from "vee-validate";
import { required } from "vee-validate/dist/rules";

extend("required", {
  ...required,
  message: field =>
    `${$nuxt.$t("fieldErr1")}${$nuxt.$t(field).toLowerCase()}${$nuxt.$t(
      "fieldErr2"
    )}`
});

Vue.component("validation-provider", ValidationProvider);
Vue.component("validation-observer", ValidationObserver);
Vue.use(VeeValidate, {
  inject: true
});

Upvotes: 2

Views: 1878

Answers (1)

ㅡichael
ㅡichael

Reputation: 23

There is no need to configure Vue.use(VeeValidation) in the plugin.

in plugin

import Vue from 'vue'
import {extend, ValidationObserver, ValidationProvider} from 'vee-validate';
import * as rules from "vee-validate/dist/rules";

Vue.component('ValidationProvider', ValidationProvider);
Vue.component("ValidationObserver", ValidationObserver);
    
for (let [rule, validation] of Object.entries(rules)) {
  // noinspection TypeScriptValidateTypes
  extend(rule, {
    ...validation
  });
}

try you vue code

<template>
      <h2 style="margin-right: 20px">Info form</h2>
      <ValidationObserver ref="form">
      <form @submit.prevent="onSubmit">
        <b-form-group>
          <label for="id">Id</label>
          <ValidationProvider name="Id" rules="required|min:5" immediate v-slot="{ errors }">
            <b-input type="text" id="id" v-model="form.id" placeholder="Enter id"></b-input>
            <span v-show="errors.length>0" class="is-invalid">{{ errors[0] }}</span>
          </ValidationProvider>
        </b-form-group>

        <b-form-group>
          <label for="name">Name</label>
          <ValidationProvider name="Name" rules="required" immediate v-slot="{ errors }">
            <b-input type="text" id="name" v-model="form.name" placeholder="Enter name"></b-input>
            <span v-show="errors.length>0" class="is-invalid">{{ errors[0] }}</span>
          </ValidationProvider>
        </b-form-group>

        <b-btn type="submit">Show my info</b-btn>
      </form>
      </ValidationObserver>

</template>

<script lang="ts">
import {Component, Vue} from 'nuxt-property-decorator';

@Component
export default class ValidationExample extends Vue {

protected onSubmit() {

    this.$refs.form.validate().then(success => {
      if (!success) {
        return;
      }

      alert('Form has been submitted!');

      // Wait until the models are updated in the UI
      this.$nextTick(() => {
        this.$refs.form.reset();
      });
    });

}
</script>

Use ref in ValidationObserver

In the example I provided, I used bootstrap and typescript.

However, it should be fully applicable to your code.

Upvotes: 1

Related Questions