mirror of
https://github.com/jakejarvis/jarv.is.git
synced 2025-04-26 09:05:22 -04:00
use zod to validate form data the "right" way
This commit is contained in:
parent
8f946d50d8
commit
b7977b8d96
@ -1,8 +1,17 @@
|
|||||||
"use server";
|
"use server";
|
||||||
|
|
||||||
|
import { headers } from "next/headers";
|
||||||
|
import { z } from "zod";
|
||||||
import { Resend } from "resend";
|
import { Resend } from "resend";
|
||||||
import config from "../../lib/config";
|
import config from "../../lib/config";
|
||||||
|
|
||||||
|
const schema = z.object({
|
||||||
|
name: z.string().min(1, { message: "Name is required" }),
|
||||||
|
email: z.string().email({ message: "Invalid email address" }),
|
||||||
|
message: z.string().min(1, { message: "Message is required" }),
|
||||||
|
["cf-turnstile-response"]: z.string().min(1, { message: "CAPTCHA not completed" }),
|
||||||
|
});
|
||||||
|
|
||||||
export async function sendMessage(
|
export async function sendMessage(
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
prevState: any,
|
prevState: any,
|
||||||
@ -10,13 +19,22 @@ export async function sendMessage(
|
|||||||
): Promise<{
|
): Promise<{
|
||||||
success: boolean;
|
success: boolean;
|
||||||
message: string;
|
message: string;
|
||||||
|
errors?: z.inferFormattedError<typeof schema>;
|
||||||
payload: FormData;
|
payload: FormData;
|
||||||
}> {
|
}> {
|
||||||
try {
|
try {
|
||||||
// these are both backups to client-side validations just in case someone squeezes through without them. the codes
|
const validatedFields = schema.safeParse({ ...formData });
|
||||||
// are identical so they're caught in the same fashion.
|
|
||||||
if (!formData || !formData.get("name") || !formData.get("email") || !formData.get("message")) {
|
// backup to client-side validations just in case someone squeezes through without them
|
||||||
return { success: false, message: "Please make sure that all fields are properly filled in.", payload: formData };
|
if (!validatedFields.success) {
|
||||||
|
console.error(validatedFields.error.flatten());
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message: "Please make sure that all fields are properly filled in.",
|
||||||
|
errors: validatedFields.error.format(),
|
||||||
|
payload: formData,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// validate captcha
|
// validate captcha
|
||||||
@ -25,12 +43,14 @@ export async function sendMessage(
|
|||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
secret: process.env.TURNSTILE_SECRET_KEY || "1x0000000000000000000000000000000AA",
|
secret: process.env.TURNSTILE_SECRET_KEY || "1x0000000000000000000000000000000AA",
|
||||||
response: formData.get("cf-turnstile-response"),
|
response: validatedFields.data["cf-turnstile-response"],
|
||||||
|
remoteip: (await headers()).get("x-forwarded-for") || "",
|
||||||
}),
|
}),
|
||||||
|
cache: "no-store",
|
||||||
});
|
});
|
||||||
const turnstileData = await turnstileResponse.json();
|
const turnstileData = await turnstileResponse?.json();
|
||||||
|
|
||||||
if (!turnstileData || !turnstileData.success) {
|
if (!turnstileData?.success) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
message: "Did you complete the CAPTCHA? (If you're human, that is...)",
|
message: "Did you complete the CAPTCHA? (If you're human, that is...)",
|
||||||
@ -41,11 +61,11 @@ export async function sendMessage(
|
|||||||
// send email
|
// send email
|
||||||
const resend = new Resend(process.env.RESEND_API_KEY);
|
const resend = new Resend(process.env.RESEND_API_KEY);
|
||||||
await resend.emails.send({
|
await resend.emails.send({
|
||||||
from: `${formData.get("name")} <${process.env.RESEND_DOMAIN ? `noreply@${process.env.RESEND_DOMAIN}` : "onboarding@resend.dev"}>`,
|
from: `${validatedFields.data.name} <${process.env.RESEND_DOMAIN ? `noreply@${process.env.RESEND_DOMAIN}` : "onboarding@resend.dev"}>`,
|
||||||
replyTo: `${formData.get("name")} <${formData.get("email")}>`,
|
replyTo: `${validatedFields.data.name} <${validatedFields.data.email}>`,
|
||||||
to: [config.authorEmail],
|
to: [config.authorEmail],
|
||||||
subject: `[${config.siteName}] Contact Form Submission`,
|
subject: `[${config.siteName}] Contact Form Submission`,
|
||||||
text: formData.get("message") as string,
|
text: validatedFields.data.message,
|
||||||
});
|
});
|
||||||
|
|
||||||
return { success: true, message: "Thanks! You should hear from me soon.", payload: formData };
|
return { success: true, message: "Thanks! You should hear from me soon.", payload: formData };
|
||||||
@ -55,6 +75,7 @@ export async function sendMessage(
|
|||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
message: "Internal server error... Try again later or shoot me an old-fashioned email?",
|
message: "Internal server error... Try again later or shoot me an old-fashioned email?",
|
||||||
|
errors: error instanceof z.ZodError ? error.format() : undefined,
|
||||||
payload: formData,
|
payload: formData,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
@ -14,17 +14,17 @@
|
|||||||
border-color: var(--colors-link);
|
border-color: var(--colors-link);
|
||||||
}
|
}
|
||||||
|
|
||||||
.input.missing {
|
|
||||||
border-color: var(--colors-error);
|
|
||||||
}
|
|
||||||
|
|
||||||
.input.textarea {
|
.input.textarea {
|
||||||
margin-bottom: 0;
|
margin-bottom: 0;
|
||||||
line-height: 1.5;
|
line-height: 1.5;
|
||||||
min-height: 10em;
|
min-height: 136px; /* approx 5 lines, to avoid severe layout shifting */
|
||||||
resize: vertical;
|
resize: vertical;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.input.invalid {
|
||||||
|
border-color: var(--colors-error);
|
||||||
|
}
|
||||||
|
|
||||||
.actionRow {
|
.actionRow {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
@ -5,7 +5,6 @@ import TextareaAutosize from "react-textarea-autosize";
|
|||||||
import Turnstile from "react-turnstile";
|
import Turnstile from "react-turnstile";
|
||||||
import clsx from "clsx";
|
import clsx from "clsx";
|
||||||
import Link from "../../components/Link";
|
import Link from "../../components/Link";
|
||||||
import useTheme from "../../hooks/useTheme";
|
|
||||||
import { sendMessage } from "./actions";
|
import { sendMessage } from "./actions";
|
||||||
import { GoCheck, GoX } from "react-icons/go";
|
import { GoCheck, GoX } from "react-icons/go";
|
||||||
import { SiMarkdown } from "react-icons/si";
|
import { SiMarkdown } from "react-icons/si";
|
||||||
@ -13,11 +12,10 @@ import { SiMarkdown } from "react-icons/si";
|
|||||||
import styles from "./form.module.css";
|
import styles from "./form.module.css";
|
||||||
|
|
||||||
const ContactForm = () => {
|
const ContactForm = () => {
|
||||||
const { theme } = useTheme();
|
const [formState, formAction, pending] = useActionState<Partial<Awaited<ReturnType<typeof sendMessage>>>, FormData>(
|
||||||
const [formState, formAction, pending] = useActionState<
|
sendMessage,
|
||||||
Partial<{ success: boolean; message: string; payload: FormData }>,
|
{}
|
||||||
FormData
|
);
|
||||||
>(sendMessage, {});
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<form action={formAction}>
|
<form action={formAction}>
|
||||||
@ -26,7 +24,7 @@ const ContactForm = () => {
|
|||||||
name="name"
|
name="name"
|
||||||
placeholder="Name"
|
placeholder="Name"
|
||||||
required
|
required
|
||||||
className={styles.input}
|
className={clsx(styles.input, formState?.errors?.name && styles.invalid)}
|
||||||
defaultValue={(formState?.payload?.get("name") || "") as string}
|
defaultValue={(formState?.payload?.get("name") || "") as string}
|
||||||
disabled={formState?.success}
|
disabled={formState?.success}
|
||||||
/>
|
/>
|
||||||
@ -37,7 +35,7 @@ const ContactForm = () => {
|
|||||||
placeholder="Email"
|
placeholder="Email"
|
||||||
required
|
required
|
||||||
inputMode="email"
|
inputMode="email"
|
||||||
className={styles.input}
|
className={clsx(styles.input, formState?.errors?.email && styles.invalid)}
|
||||||
defaultValue={(formState?.payload?.get("email") || "") as string}
|
defaultValue={(formState?.payload?.get("email") || "") as string}
|
||||||
disabled={formState?.success}
|
disabled={formState?.success}
|
||||||
/>
|
/>
|
||||||
@ -47,7 +45,7 @@ const ContactForm = () => {
|
|||||||
placeholder="Write something..."
|
placeholder="Write something..."
|
||||||
minRows={5}
|
minRows={5}
|
||||||
required
|
required
|
||||||
className={styles.input}
|
className={clsx(styles.input, styles.textarea, formState?.errors?.message && styles.invalid)}
|
||||||
defaultValue={(formState?.payload?.get("message") || "") as string}
|
defaultValue={(formState?.payload?.get("message") || "") as string}
|
||||||
disabled={formState?.success}
|
disabled={formState?.success}
|
||||||
/>
|
/>
|
||||||
@ -78,12 +76,9 @@ const ContactForm = () => {
|
|||||||
](https://jarv.is), and <code>`code`</code>.
|
](https://jarv.is), and <code>`code`</code>.
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Turnstile
|
<div style={{ margin: "1em 0" }}>
|
||||||
sitekey={process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY || "1x00000000000000000000AA"}
|
<Turnstile sitekey={process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY || "1x00000000000000000000AA"} fixedSize />
|
||||||
style={{ margin: "1em 0" }}
|
</div>
|
||||||
theme={theme === "dark" ? theme : "light"}
|
|
||||||
fixedSize
|
|
||||||
/>
|
|
||||||
|
|
||||||
<div className={styles.actionRow}>
|
<div className={styles.actionRow}>
|
||||||
{!formState?.success && (
|
{!formState?.success && (
|
||||||
|
@ -23,7 +23,7 @@ const ColorfulLink = ({
|
|||||||
{children}
|
{children}
|
||||||
</Link>
|
</Link>
|
||||||
|
|
||||||
<style>{`.${styles.page} .${uniqueId}{--colors-link:${lightColor};--colors-linkUnderline:${rgba(lightColor, 0.4)}}[data-theme="dark"] .${styles.page} .${uniqueId}{--colors-link:${darkColor};--colors-linkUnderline:${rgba(darkColor, 0.4)}}`}</style>
|
<style>{`.${uniqueId}{--colors-link:${lightColor};--colors-linkUnderline:${rgba(lightColor, 0.4)}}[data-theme="dark"] .${uniqueId}{--colors-link:${darkColor};--colors-linkUnderline:${rgba(darkColor, 0.4)}}`}</style>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
15
package.json
15
package.json
@ -22,13 +22,13 @@
|
|||||||
"@giscus/react": "^3.1.0",
|
"@giscus/react": "^3.1.0",
|
||||||
"@mdx-js/loader": "^3.1.0",
|
"@mdx-js/loader": "^3.1.0",
|
||||||
"@mdx-js/react": "^3.1.0",
|
"@mdx-js/react": "^3.1.0",
|
||||||
"@next/bundle-analyzer": "15.2.2-canary.0",
|
"@next/bundle-analyzer": "15.2.2-canary.1",
|
||||||
"@next/mdx": "15.2.2-canary.0",
|
"@next/mdx": "15.2.2-canary.1",
|
||||||
"@octokit/graphql": "^8.2.1",
|
"@octokit/graphql": "^8.2.1",
|
||||||
"@octokit/graphql-schema": "^15.26.0",
|
"@octokit/graphql-schema": "^15.26.0",
|
||||||
"@prisma/client": "^6.4.1",
|
"@prisma/client": "^6.4.1",
|
||||||
"@react-spring/web": "^9.7.5",
|
"@react-spring/web": "^9.7.5",
|
||||||
"@sentry/nextjs": "^9.3.0",
|
"@sentry/nextjs": "^9.4.0",
|
||||||
"@vercel/analytics": "^1.5.0",
|
"@vercel/analytics": "^1.5.0",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
"comma-number": "^2.1.0",
|
"comma-number": "^2.1.0",
|
||||||
@ -38,7 +38,7 @@
|
|||||||
"feed": "^4.2.2",
|
"feed": "^4.2.2",
|
||||||
"gray-matter": "^4.0.3",
|
"gray-matter": "^4.0.3",
|
||||||
"modern-normalize": "^3.0.1",
|
"modern-normalize": "^3.0.1",
|
||||||
"next": "15.2.2-canary.0",
|
"next": "15.2.2-canary.1",
|
||||||
"obj-str": "^1.1.0",
|
"obj-str": "^1.1.0",
|
||||||
"p-map": "^7.0.3",
|
"p-map": "^7.0.3",
|
||||||
"p-memoize": "^7.1.1",
|
"p-memoize": "^7.1.1",
|
||||||
@ -66,7 +66,8 @@
|
|||||||
"remark-rehype": "^11.1.1",
|
"remark-rehype": "^11.1.1",
|
||||||
"remark-smartypants": "^3.0.2",
|
"remark-smartypants": "^3.0.2",
|
||||||
"resend": "^4.1.2",
|
"resend": "^4.1.2",
|
||||||
"unified": "^11.0.5"
|
"unified": "^11.0.5",
|
||||||
|
"zod": "^3.24.2"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/eslintrc": "^3.3.0",
|
"@eslint/eslintrc": "^3.3.0",
|
||||||
@ -81,7 +82,7 @@
|
|||||||
"@types/react-is": "^19.0.0",
|
"@types/react-is": "^19.0.0",
|
||||||
"cross-env": "^7.0.3",
|
"cross-env": "^7.0.3",
|
||||||
"eslint": "~9.21.0",
|
"eslint": "~9.21.0",
|
||||||
"eslint-config-next": "15.2.2-canary.0",
|
"eslint-config-next": "15.2.2-canary.1",
|
||||||
"eslint-config-prettier": "~10.0.2",
|
"eslint-config-prettier": "~10.0.2",
|
||||||
"eslint-plugin-mdx": "~3.1.5",
|
"eslint-plugin-mdx": "~3.1.5",
|
||||||
"eslint-plugin-prettier": "~5.2.3",
|
"eslint-plugin-prettier": "~5.2.3",
|
||||||
@ -118,6 +119,8 @@
|
|||||||
"onlyBuiltDependencies": [
|
"onlyBuiltDependencies": [
|
||||||
"@prisma/client",
|
"@prisma/client",
|
||||||
"@prisma/engines",
|
"@prisma/engines",
|
||||||
|
"@sentry/cli",
|
||||||
|
"esbuild",
|
||||||
"prisma",
|
"prisma",
|
||||||
"sharp",
|
"sharp",
|
||||||
"simple-git-hooks"
|
"simple-git-hooks"
|
||||||
|
888
pnpm-lock.yaml
generated
888
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
Loading…
x
Reference in New Issue
Block a user