From 771e7f21cf332052b74c5506a8c2f38f666cae55 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Sun, 18 Sep 2022 14:02:02 +0200 Subject: [PATCH] fix: handle nested value change validation #3926 (#3929) --- packages/vee-validate/src/useField.ts | 4 ++- packages/vee-validate/tests/useField.spec.ts | 38 ++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/packages/vee-validate/src/useField.ts b/packages/vee-validate/src/useField.ts index 4583a769c..4ece9c968 100644 --- a/packages/vee-validate/src/useField.ts +++ b/packages/vee-validate/src/useField.ts @@ -219,16 +219,18 @@ function _useField( } let unwatchValue: WatchStopHandle; + let lastWatchedValue = deepCopy(value.value); function watchValue() { unwatchValue = watch( value, (val, oldVal) => { - if (isEqual(val, oldVal)) { + if (isEqual(val, oldVal) && isEqual(val, lastWatchedValue)) { return; } const validateFn = validateOnValueUpdate ? validateWithStateMutation : validateValidStateOnly; validateFn(); + lastWatchedValue = deepCopy(val); }, { deep: true, diff --git a/packages/vee-validate/tests/useField.spec.ts b/packages/vee-validate/tests/useField.spec.ts index f02b34c44..e9aa7ebc2 100644 --- a/packages/vee-validate/tests/useField.spec.ts +++ b/packages/vee-validate/tests/useField.spec.ts @@ -29,6 +29,44 @@ describe('useField()', () => { expect(error?.textContent).toBe(REQUIRED_MESSAGE); }); + // #3926 + test('validates when nested value changes', async () => { + mountWithHoc({ + setup() { + const { value, errorMessage } = useField( + 'field', + val => { + if (!val?.name) { + return REQUIRED_MESSAGE; + } + + return true; + }, + { + initialValue: { name: 'test' }, + } + ); + + onMounted(() => { + value.value.name = ''; + }); + + return { + value, + errorMessage, + }; + }, + template: ` + {{ errorMessage }} + `, + }); + + const error = document.querySelector('span'); + + await flushPromises(); + expect(error?.textContent).toBe(REQUIRED_MESSAGE); + }); + test('valid flag is correct after reset', async () => { mountWithHoc({ setup() {