Skip to content

Commit

Permalink
fix: apply schema casts when submitting closes #4565
Browse files Browse the repository at this point in the history
  • Loading branch information
logaretm committed Nov 29, 2023
1 parent ec8a4d7 commit b2203c8
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/brave-camels-wonder.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'vee-validate': patch
---

fix: apply schema casts when submitting closes #4565
6 changes: 5 additions & 1 deletion packages/vee-validate/src/useForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,10 @@ export function useForm<
{ valid: formResult.valid, results: {}, errors: {} } as FormValidationResult<TValues>,
);

if (formResult.values) {
results.values = formResult.values;
}

return results;
},
);
Expand Down Expand Up @@ -767,8 +771,8 @@ export function useForm<
*/
function resetForm(resetState?: Partial<FormState<TValues>>, 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;
Expand Down
47 changes: 47 additions & 0 deletions packages/zod/tests/zod.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string | undefined>;
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: `<div></div>`,
});

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({
Expand Down

0 comments on commit b2203c8

Please sign in to comment.