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
The ValidationObserver is a component that wraps your forms and provides aggregated validation state for all the fields nested under it using scoped slots . For more information on how to use the ValidationObserver , see Forms Guide.
All you need is to add the v-validate directive to the input you wish to validate and make sure your input has a name attribute for error messages generation. Then, pass to the directive a rules string which contains a list of validation rules separated by a pipe ' | '.
Fortunately, Nuxt comes with a ready-made production configuration that is not locked for you. That is, if you want to override any smart defaults or pre-configurations you can edit the nuxt.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With