Skip to content

Instantly share code, notes, and snippets.

@omar2205
Created February 15, 2023 07:39
Show Gist options
  • Save omar2205/f55e5fac9c53697f1312706f803991b9 to your computer and use it in GitHub Desktop.
Save omar2205/f55e5fac9c53697f1312706f803991b9 to your computer and use it in GitHub Desktop.
Parse FormData with Zod
// Using Deno :P
import { z } from 'npm:zod'
const User = z.object({
username: z.string(),
email: z.string().email()
})
function getMissingFields(error: z.ZodError): string[] {
const missingFields: string[] = []
for (const errorIssue of error.issues) {
if (errorIssue.code === 'invalid_type') {
missingFields.push(errorIssue.path[0] as string)
}
}
return missingFields
}
function main() {
const f = new FormData()
f.append('username', 'alice')
f.append('email', '[email protected]')
const u = User.safeParse(Object.fromEntries(f.entries()))
// Handle error
if (!u.success) {
console.log(getMissingFields(u.error))
return
}
console.log(u.data)
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment