Skip to content

Commit b45c3fb

Browse files
author
Philipp
committed
Returns errors object
1 parent a12c272 commit b45c3fb

File tree

3 files changed

+27
-17
lines changed

3 files changed

+27
-17
lines changed

README.md

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,10 +56,12 @@ In Vue classes:
5656
axios.post('/example', data)
5757
.then(res => {})
5858
.catch(err => {
59-
//adds errors to vee-validate errorBag and returns the first error string
60-
let firstError = this.$addLaravelErrors(err.response);
59+
//adds errors to vee-validate errorBag and returns the errors as object
60+
const errors = this.$addLaravelErrors(err.response);
6161
62-
alert(firstError); //it's a string or null
62+
if(errors){
63+
alert(errors[Object.keys(errors)[0]]);
64+
}
6365
});
6466
}
6567
}

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@pmochine/vee-validate-laravel",
3-
"version": "1.0.2",
3+
"version": "1.0.3",
44
"description": "Adds simple laravel form validation support to vee-validate",
55
"main": "src/vee-validate-laravel.js",
66
"scripts": {

src/vee-validate-laravel.js

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ const Plugin = {
1010
*
1111
* @param {obj} errorResponse [axios error.response]
1212
*
13-
* @return {?string} [returns the first error message]
13+
* @return {?obj} [returns the all errors with keys]
1414
*/
1515
function addToErrorBag(errorResponse) {
1616
// only allow this function to be run if the validator exists
@@ -25,7 +25,7 @@ function addToErrorBag(errorResponse) {
2525
// check if errors exist
2626
if (!hasProperty(errorResponse.data, 'errors')) return null;
2727

28-
return loopThroughErrors.call(this, errorResponse.data.errors);
28+
return loopThroughErrors.call(this, errorResponse.data);
2929
}
3030

3131
const hasProperty = (obj, key) => {
@@ -36,20 +36,28 @@ const hasProperty = (obj, key) => {
3636
return has.call(obj, key);
3737
};
3838

39-
function loopThroughErrors(errors) {
40-
let firstError = '';
39+
function loopThroughErrors(data) {
40+
if (!data) {
41+
return null;
42+
}
4143

42-
Object.keys(errors).forEach((field) => {
43-
this.$validator.errors.add({
44-
field,
45-
msg: errors[field].join(', '),
46-
});
44+
// Attempt to parse Laravel-structured validation errors.
45+
try {
46+
const messages = {};
47+
48+
Object.keys(data.errors).forEach((key) => {
49+
messages[key] = data.errors[key].join(', ');
4750

48-
// add the first error
49-
if (!firstError) firstError = errors[field].join(', ');
50-
});
51+
this.$validator.errors.add({
52+
field,
53+
msg: messages[key],
54+
});
55+
});
5156

52-
return firstError;
57+
return messages;
58+
} catch (e) {
59+
return data;
60+
}
5361
}
5462

5563

0 commit comments

Comments
 (0)