Skip to content

Validate a Draft Before a Write

The Course
•
18 min study

The decision

The form and the API both create Library items. Their shared rule is a domain function that accepts unknown input and returns a result, rather than relying on an HTML required attribute.

Read, predict, run

Try a valid object, whitespace, null and an object without a title. The function narrows the input before trimming. The lab form sends JSON to a Server Action so malformed shapes can be explored without a separate API client:

JavaScript
export function run(input) {
  if (!input || typeof input.title !== "string")
    return { ok: false, error: "Enter a title." };
  const title = input.title.trim();
  if (!title) return { ok: false, error: "Enter a title." };
  return { ok: true, title };
}

Before pressing Run, predict what run returns for null and {"title": " Forms "}, from the code above. Write your answers down first: after Run, the case table shows the expected values beside the actual ones.

Validate a Draft Before a Write Next.js · 7 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Study Library · Practice lab</strong> </header> {children} </body> </html> ); } import ProbeForm from "./ProbeForm.jsx"; import { examples } from "@/lib/contract.js"; import Cases from "./Cases.jsx"; export default function Page() { return ( <main> <h1>Validate a Draft Before a Write</h1> <p> Read the input and predict the result before running. Change lib/contract.js for the exercise. </p> <ProbeForm initial={examples[0][0]} /> <Cases /> </main> ); } "use server"; import { run } from "@/lib/contract.js"; export async function evaluate(previous, formData) { const raw = formData.get("input"); if (typeof raw !== "string") return { error: "Enter JSON.", result: null }; let input; try { input = JSON.parse(raw); } catch { return { error: "Enter valid JSON.", result: null }; } try { return { error: null, result: await run(input) }; } catch { return { error: "That input could not be evaluated.", result: null }; } } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } "use client"; import { useActionState } from "react"; import { evaluate } from "./actions.js"; export default function ProbeForm({ initial }) { const [state, action, pending] = useActionState(evaluate, { error: null, result: null, }); return ( <form action={action}> <label> Input JSON{" "} <textarea name="input" defaultValue={JSON.stringify(initial)} rows={3} /> </label> <button disabled={pending}>{pending ? "Evaluating…" : "Evaluate"}</button> <p role="alert">{state.error}</p> <pre role="status"> {state.result === null ? "" : JSON.stringify(state.result)} </pre> </form> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } export function run(input) { if (!input || typeof input.title !== "string") return { ok: false, error: "Enter a title." }; const title = input.title.trim(); if (!title) return { ok: false, error: "Enter a title." }; return { ok: true, title }; } export const examples = [ [null, { ok: false, error: "Enter a title." }], [{ title: " Forms " }, { ok: true, title: "Forms" }], ];
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Check your prediction
  • Input null → {"ok": false, "error": "Enter a title."}.
  • Input {"title": " Forms "} → {"ok": true, "title": "Forms"}.

The case table computes these results on the server side of the simulation. It compares values; it does not prove a production deployment or database works.

The failure to avoid

String(null) is the word null, not an empty field. A permissive conversion can make missing or File values look like real titles.

Trace {"title": " "} and then null through run. Which return handles each, and why must the typeof check come before trim()?

Exercise

Extend the contract

Reject a trimmed title longer than 60 characters with Keep it to 60 characters. Exactly 60 must pass.

Edit lib/contract.js, then rerun the original cases. If the requested rule changes an earlier result, update that expected value deliberately. Keep the other cases. Add the acceptance cases to examples so the preview checks them too.

  • Input {"title": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"} must return {"ok": false, "error": "Keep it to 60 characters."}.
Your working space Next.js · 7 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Study Library · Practice lab</strong> </header> {children} </body> </html> ); } import ProbeForm from "./ProbeForm.jsx"; import { examples } from "@/lib/contract.js"; import Cases from "./Cases.jsx"; export default function Page() { return ( <main> <h1>Validate a Draft Before a Write</h1> <p> Read the input and predict the result before running. Change lib/contract.js for the exercise. </p> <ProbeForm initial={examples[0][0]} /> <Cases /> </main> ); } "use server"; import { run } from "@/lib/contract.js"; export async function evaluate(previous, formData) { const raw = formData.get("input"); if (typeof raw !== "string") return { error: "Enter JSON.", result: null }; let input; try { input = JSON.parse(raw); } catch { return { error: "Enter valid JSON.", result: null }; } try { return { error: null, result: await run(input) }; } catch { return { error: "That input could not be evaluated.", result: null }; } } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } "use client"; import { useActionState } from "react"; import { evaluate } from "./actions.js"; export default function ProbeForm({ initial }) { const [state, action, pending] = useActionState(evaluate, { error: null, result: null, }); return ( <form action={action}> <label> Input JSON{" "} <textarea name="input" defaultValue={JSON.stringify(initial)} rows={3} /> </label> <button disabled={pending}>{pending ? "Evaluating…" : "Evaluate"}</button> <p role="alert">{state.error}</p> <pre role="status"> {state.result === null ? "" : JSON.stringify(state.result)} </pre> </form> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } export function run(input) { if (!input || typeof input.title !== "string") return { ok: false, error: "Enter a title." }; const title = input.title.trim(); if (!title) return { ok: false, error: "Enter a title." }; return { ok: true, title }; } export const examples = [ [null, { ok: false, error: "Enter a title." }], [{ title: " Forms " }, { ok: true, title: "Forms" }], ];
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Hint 1: the idea

A length limit is one more way a draft can be invalid. It applies to what will be saved, so it's measured after the draft has been cleaned up.

Hint 2: a first step

Place the length check after trimming and before returning success.

Show one solution

Replace the exported run function and any constants shown here; keep the examples export underneath it. Compare the result with your own approach.

JavaScript
export function run(input) {
  if (!input || typeof input.title !== "string")
    return { ok: false, error: "Enter a title." };
  const title = input.title.trim();
  if (!title) return { ok: false, error: "Enter a title." };
  if (title.length > 60)
    return { ok: false, error: "Keep it to 60 characters." };
  return { ok: true, title };
}

The check uses the trimmed title, so spaces around a 60-character title don't push it over. It comes after the blank check, so an empty draft still gets Enter a title., the more useful message. > 60 lets exactly 60 through, as the brief asks: a case at 60 and one at 61 pin the boundary.

Explain it without the code

The form could also use maxLength={60} on the input. Explain in two sentences why the Server Action still checks.

Going further

Read the Next.js guide for the framework boundary around this rule. The preview runs code-playpad's Next.js simulation. Real caching, hydration, authentication and persistence require the real-server checks described on Day 7.

Was this article helpful?

Your response is saved on this device.