feat: 添加创建代码片段界面内容验证

This commit is contained in:
ngc2207 2024-11-12 17:06:10 +08:00
parent 3474cb11af
commit a817f718d5
2 changed files with 45 additions and 20 deletions

View File

@ -17,3 +17,32 @@ export async function deleteSnippet(id: number) {
redirect("/"); redirect("/");
} }
export async function createSnippet(
formState: { message: string },
formData: FormData
) {
// Check the user's inputs and make sure they're valid
const title = formData.get("title");
const code = formData.get("code");
if (typeof title !== "string" || title.length < 3) {
return {
message: "Title must be longer",
};
}
if (typeof code !== "string" || code.length < 10) {
return {
message: "Code must be longer",
};
}
// Create a new record in the database
const snippet = await db.snippet.create({
data: {
title: title,
code: code,
},
});
console.log(snippet);
// Redirect the user back to the root route
redirect("/");
}

View File

@ -1,26 +1,15 @@
import { db } from "@/db"; "use client";
import { redirect } from "next/navigation";
import * as actions from "@/actions";
import { useActionState } from "react";
export default function SnippetCreatePage() { export default function SnippetCreatePage() {
async function createSnippet(formData: FormData) { const [formState, action] = useActionState(actions.createSnippet, {
// This needs to be a server action! message: "",
"use server"; });
// Check the user's inputs and make sure they're valid
const title = formData.get("title") as string;
const code = formData.get("code") as string;
// Create a new record in the database
const snippet = await db.snippet.create({
data: {
title: title,
code: code,
},
});
console.log(snippet);
// Redirect the user back to the root route
redirect("/");
}
return ( return (
<form action={createSnippet}> <form action={action}>
<h3 className="font-bold m-3">Create a Snippet</h3> <h3 className="font-bold m-3">Create a Snippet</h3>
<div className="flex flex-col gap-4"> <div className="flex flex-col gap-4">
<div className="flex gap-4"> <div className="flex gap-4">
@ -39,6 +28,13 @@ export default function SnippetCreatePage() {
</label> </label>
<input name="code" className="border rounded p-2 w-full" id="code" /> <input name="code" className="border rounded p-2 w-full" id="code" />
</div> </div>
{formState.message ? (
<div className="my-2 p-2 bg-red-200 border rounded border-red-400">
{formState.message}
</div>
) : null}
<button type="submit" className="rounded p-2 bg-blue-200"> <button type="submit" className="rounded p-2 bg-blue-200">
Create Create
</button> </button>