Created
February 15, 2023 07:39
-
-
Save omar2205/f55e5fac9c53697f1312706f803991b9 to your computer and use it in GitHub Desktop.
Parse FormData with Zod
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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