T
TanStack8mo ago
yappiest-sapphire

Validator schema as subset of default values

So I've a form where I temporarily keep some values, which are set in my default values but on submit, they are discarded by the zod schema. For example:
const product = {id: 0, name: "Beef burger", userId: currentUser.id, user: {id: currentUser.id, name: currentUser.name } }

const saveProductSchema = z.object({ id: z.number(), name: z.string().min(1).max(50), userId: z.number().min(1) });

const form = useAppForm({
defaultValues: product,
validators: {
onSubmit: saveProductSchema,
},
onSubmit: async ({ value }) => {
// submit logic.

},
});
const product = {id: 0, name: "Beef burger", userId: currentUser.id, user: {id: currentUser.id, name: currentUser.name } }

const saveProductSchema = z.object({ id: z.number(), name: z.string().min(1).max(50), userId: z.number().min(1) });

const form = useAppForm({
defaultValues: product,
validators: {
onSubmit: saveProductSchema,
},
onSubmit: async ({ value }) => {
// submit logic.

},
});
In current implementation, it'll give error because schema has user missing. I need user object in my form for displaying purposes so I can't just cast defaultValues to schema type.
3 Replies
extended-salmon
extended-salmon8mo ago
if it's only for displaying purposes, why is it in the defaultValues? can they be changed? do they need validation?
yappiest-sapphire
yappiest-sapphireOP8mo ago
Yes, such objects can be changed. Example if a stock item has a product in it, I only wanna send productId when saving. But I may need to update UI based on selected product. Eg my Product Autocomplete onChange could look like this:-
e => {
field.handleChange(e.target.value); // storing productId that is required for submitting form

form.setValue("product", e.target.selectedItem); // temporarily storing product so I can display its details on UI
}
e => {
field.handleChange(e.target.value); // storing productId that is required for submitting form

form.setValue("product", e.target.selectedItem); // temporarily storing product so I can display its details on UI
}
And no, product is not validated in this case. Its just stored temporarily for displaying info. When form is submitted, zod will just remove it from the payload sent to the server.
extended-salmon
extended-salmon8mo ago
sounds like a use case for Form.Subscribe subscribe to productId and display related information

Did you find this page helpful?