Skip to content

Commit

Permalink
feat: add zod example
Browse files Browse the repository at this point in the history
  • Loading branch information
berkinanik committed Aug 27, 2023
1 parent 87b89ea commit f55d2d7
Show file tree
Hide file tree
Showing 14 changed files with 640 additions and 0 deletions.
4 changes: 4 additions & 0 deletions zod/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/** @type {import('eslint').Linter.Config} */
module.exports = {
extends: ["@remix-run/eslint-config", "@remix-run/eslint-config/node"],
};
6 changes: 6 additions & 0 deletions zod/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
node_modules

/.cache
/build
/public/build
.env
49 changes: 49 additions & 0 deletions zod/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Zod Example

This example demonstrates how to use [Zod](https://npm.im/zod) for server-side validation and data transformation in a Remix application. It includes a user registration form and a product listing page.

In the user registration form, Zod is used to validate and transform POST data which is submitted by the form in the action handler.

In the product listing page, Zod is used to validate and transform GET query parameters which are used for filtering and pagination in the loader.

Every validation and data transformation is done on the server-side, so the client can use the app without JavaScript enabled.

Enjoy Remix's progressively enhanced forms 💿 and Zod's type safety 💎!

## Preview

Open this example on [CodeSandbox](https://codesandbox.com):

[![Open in CodeSandbox](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/github/remix-run/examples/tree/main/zod)

## Example

### `app/root.tsx`

A simple error boundary component is added to catch the errors and display error messages.

### `app/routes/index.tsx`

This file contains the user registration form and its submission handling logic. It leverages Zod for validating and transforming the POST data.

### `app/routes/products.tsx`

This file implements the product listing page, including filters and pagination. It leverages Zod for URL query parameter validation and transforming. A cache control header is added to the response to ensure the page is cached also.

---

Following two files are used for mocking and functionality demonstration. They are not directly related to Zod or Remix.

#### `app/lib/product.server.ts`

This file defines the schema for the product data and provides a mock product list. It's used to ensure the type safety of the product data.

#### `app/lib/utils.server.ts`

This file contains `isDateFormat` utility which is used for date validation for `<input type="date" />` and a function for calculating days until the next birthday.

## Related Links

- [Remix Documentation](https://remix.run/docs)
- [Zod Documentation](https://github.com/colinhacks/zod/#zod)
- [Zod: Coercion for Primitives](https://github.com/colinhacks/zod/#coercion-for-primitives)
87 changes: 87 additions & 0 deletions zod/app/lib/product.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import * as z from "zod";

const ProductSchema = z.object({
id: z.number().int().positive(),
name: z.string(),
price: z.number(),
});

type Product = z.infer<typeof ProductSchema>;

export const mockProducts: Product[] = [
{
id: 1,
name: "Laptop",
price: 900,
},
{
id: 2,
name: "Smartphone",
price: 700,
},
{
id: 3,
name: "T-shirt",
price: 20,
},
{
id: 4,
name: "Jeans",
price: 50,
},
{
id: 5,
name: "Running Shoes",
price: 90,
},
{
id: 6,
name: "Bluetooth Speaker",
price: 50,
},
{
id: 7,
name: "Dress Shirt",
price: 30,
},
{
id: 8,
name: "Gaming Console",
price: 350,
},
{
id: 9,
name: "Sneakers",
price: 120,
},
{
id: 10,
name: "Watch",
price: 200,
},
{
id: 11,
name: "Hoodie",
price: 40,
},
{
id: 12,
name: "Guitar",
price: 300,
},
{
id: 13,
name: "Fitness Tracker",
price: 80,
},
{
id: 14,
name: "Backpack",
price: 50,
},
{
id: 15,
name: "Dumbbell Set",
price: 130,
},
];
16 changes: 16 additions & 0 deletions zod/app/lib/utils.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export const isDateFormat = (date: string): boolean => {
return /^\d{4}-\d{2}-\d{2}$/.test(date);
};

export const calculateDaysUntilNextBirthday = (birthday: Date): number => {
const today = new Date();
const currentYear = today.getFullYear();
const birthdayThisYear = new Date(
currentYear,
birthday.getMonth(),
birthday.getDate(),
);
const diff = birthdayThisYear.getTime() - today.getTime();
const days = Math.ceil(diff / (1000 * 3600 * 24));
return days < 0 ? 365 + days : days;
};
41 changes: 41 additions & 0 deletions zod/app/root.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import type { MetaFunction } from "@remix-run/node";
import {
Links,
LiveReload,
Meta,
Outlet,
Scripts,
ScrollRestoration,
} from "@remix-run/react";

export const meta: MetaFunction = () => ({
charset: "utf-8",
title: "Remix 💿 + Zod 💎",
viewport: "width=device-width,initial-scale=1",
});

export default function App() {
return (
<html lang="en">
<head>
<Meta />
<Links />
</head>
<body>
<Outlet />
<ScrollRestoration />
<Scripts />
<LiveReload />
</body>
</html>
);
}

export const ErrorBoundary = ({ error }: { error: Error }) => {
return (
<div>
<h1>App Error</h1>
<pre>{error.message}</pre>
</div>
);
};
170 changes: 170 additions & 0 deletions zod/app/routes/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
import { ActionArgs, json } from "@remix-run/node";
import { Form, Link, useActionData, useNavigation } from "@remix-run/react";
import * as z from "zod";

import {
calculateDaysUntilNextBirthday,
isDateFormat,
} from "~/lib/utils.server";

export const action = async ({ request }: ActionArgs) => {
const formData = await request.formData();
const payload = Object.fromEntries(formData.entries());

const currentDate = new Date();

const schema = z.object({
firstName: z
.string()
.min(2, "Must be at least 2 characters")
.max(50, "Must be less than 50 characters"),
email: z.string().email("Must be a valid email"),
birthday: z.coerce
.date()
.min(
new Date(
currentDate.getFullYear() - 26,
currentDate.getMonth(),
currentDate.getDate(),
),
"Must be at younger than 25",
)
.max(
new Date(
currentDate.getFullYear() - 18,
currentDate.getMonth(),
currentDate.getDate(),
),
"Must be at least 18 years old",
),
});

const parseResult = schema.safeParse(payload);

if (!parseResult.success) {
const fields = {
firstName: typeof payload.firstName === "string" ? payload.firstName : "",
email: typeof payload.email === "string" ? payload.email : "",
birthday:
typeof payload.birthday === "string" && isDateFormat(payload.birthday)
? payload.birthday
: "",
};

return json(
{
fieldErrors: parseResult.error.flatten().fieldErrors,
fields,
message: null,
},
{
status: 400,
},
);
}

return json({
fieldErrors: null,
fields: null,
message: `Hello ${parseResult.data.firstName}! We will send an email to ${
parseResult.data.email
} for your discount code in ${calculateDaysUntilNextBirthday(
parseResult.data.birthday,
)} days.`,
});
};

const errorTextStyle: React.CSSProperties = {
fontWeight: "bold",
color: "red",
marginInline: 0,
marginBlock: "0.25rem",
};

export default function RegisterView() {
const actionData = useActionData<typeof action>();
const navigation = useNavigation();
const isSubmitting = navigation.state === "submitting";

if (actionData?.message) {
return (
<div>
<h3>{actionData.message}</h3>
<hr />
<Link to="/products">View Products</Link>
</div>
);
}

return (
<div>
<h1>Register for a birthday discount!</h1>
<Form method="post">
<div>
<label htmlFor="firstName">First Name:</label>
<input
type="text"
id="firstName"
name="firstName"
defaultValue={actionData?.fields?.firstName}
/>
{actionData?.fieldErrors?.firstName
? actionData.fieldErrors.firstName.map((error, index) => (
<p style={errorTextStyle} key={`first-name-error-${index}`}>
{error}
</p>
))
: null}
</div>

<br />

<div>
<label htmlFor="email">Email:</label>
<input
type="email"
id="email"
name="email"
defaultValue={actionData?.fields?.email}
/>
{actionData?.fieldErrors?.email
? actionData.fieldErrors.email.map((error, index) => (
<p style={errorTextStyle} key={`email-error-${index}`}>
{error}
</p>
))
: null}
</div>

<br />

<div>
<label htmlFor="birthday">Birthday:</label>
<input
type="date"
id="birthday"
name="birthday"
defaultValue={actionData?.fields?.birthday}
/>
{actionData?.fieldErrors?.birthday
? actionData.fieldErrors.birthday.map((error, index) => (
<p style={errorTextStyle} key={`birthday-error-${index}`}>
{error}
</p>
))
: null}
</div>

<br />

<button type="submit" disabled={isSubmitting}>
Register
</button>
</Form>
<hr />
<Link to="/products" prefetch="intent">
View Products
</Link>
</div>
);
}
Loading

0 comments on commit f55d2d7

Please sign in to comment.