mirror of
https://github.com/jakejarvis/jarv.is.git
synced 2025-07-03 12:46:38 -04:00
use zod to validate form data the "right" way
This commit is contained in:
@ -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>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
Reference in New Issue
Block a user