5
votes

Im using Nuxt js + veeValidate 3.x

my plugin looks like this:

import Vue from 'vue'
import {
  ValidationObserver,
  ValidationProvider,
  extend
} from 'vee-validate'
import { required, email, min, confirmed } from 'vee-validate/dist/rules'

extend('required', {
  ...required,
  message: 'This field is required'
})
extend('email', email)
extend('min', min)
extend('confirmed', confirmed)
Vue.component('ValidationProvider', ValidationProvider)
Vue.component('ValidationObserver', ValidationObserver) 

Added as a plugin into nuxt.config.js plugins: [{ src: '~/plugins/vee-validate.js', ssr: false }, .. The template looks like this:

<ValidationObserver ref="registrationForm"> 
   <ValidationProvider rules="required|email" name="Email Address" v-slot="{ errors }">
    <div>
     <input type="text" v-model.lazy="user.email"/>
     <span class=form-errors">{{ errors[0] }}</span>
    </div>
   </ValidationProvider>
</ValidationObserver>

The validation works perfectly this way:

methods: {
   async submit() {
      const isValid = await this.$refs.registrationForm.validate()
      if (isValid) {
        this.register()
     ....

But I may get some errors from the API side during the execution of this.register() (Ex: error: email is already exists). How do I push received errors into validating errors array (if there such)? the old way as this.errors.add() doesn't work (of course) anymore. I've read about ErrorBag, but I just dont understand how do I import/export it in the plugin

1

1 Answers

4
votes

Finally I found the answer here:

https://logaretm.github.io/vee-validate/advanced/server-side-validation.html#handling-backend-validation

which is called "Handling Backend Validation"

In short the answer is :

....
this.$refs.registrationForm.setErrors({ email: ['Your email does\'t look good enough! Try again!'] })
...

Will display the error below the input field

PS: If you work with Laravel as backend, error handling will work just out of the box:

// try,async stuff sending data to the endpoint
...
catch (error) {
   this.$refs.registrationForm.setErrors(error.response.data.errors)
}