Z
Zod7mo ago
Haddok

Haddok - Hi everyone , i have to use zod in my ...

Hi everyone , i have to use zod in my javascript environment i have defined a schema , that has multiple fields the entire schema validation works perfectly , but for javascript i am not sure how to use schema.shape.safeparse for onchange validation as the the error is .shape is undefined , can anyone guide me what to do ? or is it possible ? any help will be greatly appreciated
Solution:
Hi there , thank you for your answer So basically i have a schema like this ```js ...
Jump to solution
8 Replies
janglad
janglad7mo ago
You can call parse/safeParse straight on the schema so schema.safeParse shape allows you to access nested keys if that's what you would want
const test = z.object({
hello: z.string()
})

test.shape.hello.parse("world")
const test = z.object({
hello: z.string()
})

test.shape.hello.parse("world")
Solution
Haddok
Haddok7mo ago
Hi there , thank you for your answer So basically i have a schema like this
const testSchema = z.object({
hello: z.string(),
there: z.number(),
this : z.string(),
is: z.number()
})
const testSchema = z.object({
hello: z.string(),
there: z.number(),
this : z.string(),
is: z.number()
})
what i want to do is use the schema to validate the data before i submit the form , which works fine , but also make each key validate on change of their respective input field. i wrote something like this - >
const handleOnchangeInput = (fieldname, value) => {
console.log(testSchema.shape[fieldname].safeParse(value))
setTest({...test, [fieldname] : value})
}
const handleOnchangeInput = (fieldname, value) => {
console.log(testSchema.shape[fieldname].safeParse(value))
setTest({...test, [fieldname] : value})
}
it has to be javascript. but here the error comes that shape is undefined . EDIT: After a few trial and error i found out , that for javascript what i had to change was add a sourcetype call before the shape call --
const handleOnchangeInput = (fieldname, value) => {
console.log(testSchema.sourceType().shape[fieldname].safeParse(value))
setTest({...test, [fieldname] : value})
}
const handleOnchangeInput = (fieldname, value) => {
console.log(testSchema.sourceType().shape[fieldname].safeParse(value))
setTest({...test, [fieldname] : value})
}
Thanks @janglad
janglad
janglad7mo ago
glad it works but wait where is the sourceType function even coming from? Is testSchema wrapped with anything? oohhh I assume you have a refine/transform after your schema?
Haddok
HaddokOP7mo ago
yes, my schema is basically adressschema where i have addressline1 2 and 3 , then type , country , state, city ,zip i have a superRefine to validate zip based on countrycode .
janglad
janglad7mo ago
yes in that case you would indeed need it
Haddok
HaddokOP7mo ago
oh so if i am not transforming anything , then the shape would work directly ?
janglad
janglad7mo ago
yes
Haddok
HaddokOP7mo ago
Want results from more Discord servers?
Add your server