You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Currently, the Zod Validator does not support validation for either JSON or Form. But, you can write the middleware like the following or middleware to support it.
import{Hono,MiddlewareHandler}from'hono'import{zValidator}from'@hono/zod-validator'import{z}from'zod'import{createMiddleware}from'hono/factory'constschema=z.object({foo: z.string()})constapp=newHono()constor=(...handlers: MiddlewareHandler[])=>createMiddleware(async(c,next)=>{letisValid=falsefor(consthandlerofhandlers){constres=awaithandler(c,next)if(res&&res.status===200){isValid=truebreak}}if(!isValid){returnc.json({valid: false},400)}})app.post('/',or(zValidator('form',schema),zValidator('json',schema)),(c)=>{// @ts-expect-error `or` does not support infer `json`constjsonData=c.req.valid('json')// @ts-expect-error `or` does not support infer `form`constformData=c.req.valid('form')returnc.json({ jsonData, formData })})constjsonRes=awaitapp.request('/',{method: 'POST',body: JSON.stringify({foo: 'bar'}),headers: {'content-type': 'application/json'}})console.log(jsonRes.status)// 200console.log(awaitjsonRes.json())constform=newFormData()form.append('foo','bar')constformRes=awaitapp.request('/',{method: 'POST',body: form})console.log(formRes.status)// 200console.log(awaitformRes.json())
how to to support both form and json body with
zValidator
?docs say that multiple validators can be used together i.e.
and
can even be used together. However they always through an error, thus neither
form
orjson
body is allowed.The text was updated successfully, but these errors were encountered: