Skip to content

Commit

Permalink
feat: propagate observer setErrors to its child observers (#2380)
Browse files Browse the repository at this point in the history
  • Loading branch information
Borzik authored and logaretm committed Sep 26, 2019
1 parent 5136f2a commit 1e567cc
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 1 deletion.
2 changes: 1 addition & 1 deletion docs/guide/validation-observer.md
Expand Up @@ -152,7 +152,7 @@ export default {

While you can add errors manually to `ValidationProvider` with the `setErrors` method, it can be annoying to do so for multiple fields at once.

The `ValidationObserver` exposes a `setErrors` method that can set errors for its children providers.
The `ValidationObserver` exposes a `setErrors` method that can set errors for its children providers and observers.

```vue
<template>
Expand Down
4 changes: 4 additions & 0 deletions src/components/Observer.ts
Expand Up @@ -248,6 +248,10 @@ export const ValidationObserver = (Vue as withObserverNode).extend({

provider.setErrors(errors[key] || []);
});

this.observers.forEach((observer: any) => {
observer.setErrors(errors);
});
}
}
});
48 changes: 48 additions & 0 deletions tests/providers/observer.js
Expand Up @@ -490,3 +490,51 @@ test('Sets errors for all providers', async () => {
expect(wrapper.find('#error1').text()).toBe('wrong');
expect(wrapper.find('#error2').text()).toBe('whoops');
});

test('Sets errors for nested observer providers', async () => {
const wrapper = mount(
{
data: () => ({
field1: '',
field2: ''
}),
template: `
<div>
<ValidationObserver ref="observer">
<ValidationObserver>
<ValidationProvider
vid="field1"
v-slot="{ errors }"
>
<input type="text" v-model="field1">
<span id="error1">{{ errors[0] }}</span>
</ValidationProvider>
<ValidationProvider
name="field2"
v-slot="{ errors }"
>
<input type="text" v-model="field2">
<span id="error2">{{ errors[0] }}</span>
</ValidationProvider>
</ValidationObserver>
</ValidationObserver>
</div>
`
},
{ localVue: Vue }
);

await flushPromises();
expect(wrapper.find('#error1').text()).toBe('');
expect(wrapper.find('#error2').text()).toBe('');

wrapper.vm.$refs.observer.setErrors({
field1: ['wrong'],
field2: ['whoops']
});

await flushPromises();
expect(wrapper.find('#error1').text()).toBe('wrong');
expect(wrapper.find('#error2').text()).toBe('whoops');
});

0 comments on commit 1e567cc

Please sign in to comment.