Skip to content

Instantly share code, notes, and snippets.

@fnky
Last active December 15, 2023 19:56
Show Gist options
  • Save fnky/7fe414b402baf5c9ba8f7ddecfdd263e to your computer and use it in GitHub Desktop.
Save fnky/7fe414b402baf5c9ba8f7ddecfdd263e to your computer and use it in GitHub Desktop.
Remix Form validation with zod
import { json, ActionFunction, useActionData, Form } from "remix";
import { z } from "zod";
// This type infer errors from a ZodType, as produced by `flatten()` of a parsed schema.
type inferSafeParseErrors<T extends z.ZodType<any, any, any>, U = string> = {
formErrors: U[];
fieldErrors: {
[P in keyof z.infer<T>]?: U[];
};
};
const LoginFields = z.object({
username: z.string().nonempty(),
password: z.string().nonempty(),
});
type LoginFields = z.infer<typeof LoginFields>;
type LoginFieldsErrors = inferSafeParseErrors<typeof LoginFields>;
type ActionData = {
fields: LoginFields;
errors?: LoginFieldsErrors;
};
const badRequest = (data: ActionData) => json(data, { status: 400 });
export const action: ActionFunction = async ({ request }) => {
const formData = await request.formData();
// The type assertion is needed because FormData can be `File` or `string`,
// but doesn't safely conform to the `LoginFields` type.
const fields = Object.fromEntries(formData.entries()) as LoginFields;
const result = LoginFields.safeParse(fields);
if (!result.success) {
return badRequest({
fields,
errors: result.error.flatten(),
});
}
return json({ fields });
};
export default function Login() {
let data = useActionData<ActionData>();
return (
<Form method="post">
<div>
<label htmlFor="username">Username:</label>
<input
id="username"
name="username"
type="text"
defaultValue={data?.fields.username}
style={{
borderColor: data?.errors?.fieldErrors.username ? "red" : "",
}}
/>
<div>{data?.errors?.fieldErrors.username}</div>
<label htmlFor="username">Password:</label>
<input
id="password"
name="password"
type="password"
style={{
borderColor: data?.errors?.fieldErrors.password ? "red" : "",
}}
/>
<div>{data?.errors?.fieldErrors.password}</div>
<button type="submit">Login</button>
</div>
</Form>
);
}
@fnky
Copy link
Author

fnky commented Nov 1, 2022

@selbekk Depends on your setup. But you can see the official stacks for a more real world example. The example doesn't seem to use zod, so if you still want to stick with zod, which I recommend, you can just ignore the validation code in there and directly go to the user verification.

Also note the inferSafeParseErrors type in this example is built in to zod itself. This example was created before that was the case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment