diff --git a/.changeset/brave-camels-wonder.md b/.changeset/brave-camels-wonder.md new file mode 100644 index 000000000..a7e25269a --- /dev/null +++ b/.changeset/brave-camels-wonder.md @@ -0,0 +1,5 @@ +--- +'vee-validate': patch +--- + +fix: apply schema casts when submitting closes #4565 diff --git a/packages/vee-validate/src/useForm.ts b/packages/vee-validate/src/useForm.ts index 47d9ea943..f7e9296df 100644 --- a/packages/vee-validate/src/useForm.ts +++ b/packages/vee-validate/src/useForm.ts @@ -426,6 +426,10 @@ export function useForm< { valid: formResult.valid, results: {}, errors: {} } as FormValidationResult, ); + if (formResult.values) { + results.values = formResult.values; + } + return results; }, ); @@ -767,8 +771,8 @@ export function useForm< */ function resetForm(resetState?: Partial>, opts?: ResetFormOpts) { let newValues = deepCopy(resetState?.values ? resetState.values : originalInitialValues.value); - newValues = isTypedSchema(schema) && isCallable(schema.cast) ? schema.cast(newValues) : newValues; newValues = opts?.force ? newValues : merge(originalInitialValues.value, newValues); + newValues = isTypedSchema(schema) && isCallable(schema.cast) ? schema.cast(newValues) : newValues; setInitialValues(newValues); mutateAllPathState(state => { state.__flags.pendingReset = true; diff --git a/packages/zod/tests/zod.spec.ts b/packages/zod/tests/zod.spec.ts index 053fd5fe4..ed6a863aa 100644 --- a/packages/zod/tests/zod.spec.ts +++ b/packages/zod/tests/zod.spec.ts @@ -356,6 +356,53 @@ test('uses zod default values for initial values', async () => { ); }); +test('uses zod transforms values for submitted values', async () => { + const onSubmitSpy = vi.fn(); + let onSubmit!: () => void; + let model!: Ref; + mountWithHoc({ + setup() { + const schema = toTypedSchema( + z + .object({ + random: z.string().min(3), + }) + .transform(() => { + return { + random: 'modified', + }; + }), + ); + + const { handleSubmit, defineField } = useForm({ + validationSchema: schema, + }); + + model = defineField('random')[0]; + + // submit now + onSubmit = handleSubmit(onSubmitSpy); + + return { + schema, + }; + }, + template: `
`, + }); + + await flushPromises(); + model.value = 'test'; + onSubmit(); + await flushPromises(); + await expect(onSubmitSpy).toHaveBeenCalledTimes(1); + await expect(onSubmitSpy).toHaveBeenLastCalledWith( + expect.objectContaining({ + random: 'modified', + }), + expect.anything(), + ); +}); + test('reset form should cast the values', async () => { const valueSpy = vi.fn(); mountWithHoc({