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