Push a custom error message to ValidationObserver
Asked Answered
S

1

6

I'm using Nuxt + 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

Sensitometer answered 26/12, 2019 at 7:26 Comment(0)
S
6

Use vee-validate's .setErrors()

Finally I found the answer here: Handling Backend Validation

When you get a return from the API on the submission attempt, you can tell the user about errors by seting a custom error message, for example:

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

...or you could just pass the error message sent from the API. In this example we're going it on the catch():

catch (error) {
   this.$refs.registrationForm.setErrors(error.response.data.errors)
}
Sensitometer answered 26/12, 2019 at 7:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.