The super simple JS package that will handle your Laravel errors and automatically inject them into a VeeValidate instance ✨
npm i laravel-veevalidate
or
yarn add laravel-veevalidate
Assuming you already have VeeValidate installed, you can use Laravel VeeValidate as a Vue Prototype.
import LaravelValidator from 'laravel-veevalidate';
Vue.prototype.$laravelValidator = LaravelValidator;
Alternatively, you can use it on a on a component-to-component basis.
import LaravelValidator from 'laravel-veevalidate';
To use the error handler with Axios, you will need to place the handleError method inside of the catch() block of the Axios promise.
The first parameter you must provide is the VeeValidate instance you would like to use. It's recommended to use the global directive ($validator). The second parameter is the response callback which Axios provides.
axios(...)
.catch(error_response => {
this.$laravelValidator.handleError(this.$validator, error_response)
})
To use the error handler with Fetch, you will need to place the handleFetchError method inside of the then() block of the Fetch promise.
The first parameter you must provide is the VeeValidate instance you would like to use. It's recommended to use the global directive ($validator). The second parameter is the response callback which Fetch provides.
fetch(...)
.then(response => {
this.$laravelValidator.handleFetchError(this.$validator, response)
})
Important: Laravel VeeValidate does not clear your VeeValidate errors. Before your request you should clear the error bag from your VeeValidate Instance:
// e.g:
this.$validator.errors.clear();
Sometimes your Request/Eloquent attributes won't match your VeeValidate fields/names. You can really easily "map" this by passing a key value object as a third parameter.
// Axios
this.$laravelValidator.handleError(this.$validator, error_response, {
'email_address': 'email address', // Attribute => Field Name
})
})
// Fetch
this.$laravelValidator.handleFetchError(this.$validator, response, {
'email_address': 'email address', // Attribute => Field Name
})
})
Laravel VeeValidate provides some simple options which you can pass as the fourth parameter of the handleError and handleFetchError methods.
Option | Description | Type | Default Value | Choices |
---|---|---|---|---|
driver | Request driver you are using. | String | axios |
axios fetch
|
show_errors | Display console errors while in Development mode | Boolean | true |
true false
|
this.$laravelValidator.handleError(this.$validator, error_response, {}, {
show_errors: false
})
This is my first JS/NPM package, I really hope it's been useful to you, if you like my work and want to show some love, consider buying me some coding fuel (Coffee) ❤