Forms, Validation & Errors
By the end of this lesson BookShelf readers will be able to write a review from the book page. The form will check simple mistakes before sending anything, show each Django error next to the right field, show whole-form errors such as "you already reviewed this book" at the top, and never send the same review twice.
What you should know first: Routing with React Router (this lesson continues its code), the error shapes from Django REST Framework Basics and Models & Serializers, and React's Forms & Controlled Inputs. For bigger forms see Form Validation at Scale. Versions: React 19.3.1, Django 6.1.3, Django REST Framework 3.18.3.
Two layers of checks
A form has two checkpoints, like a railway journey. The ticket checker on the platform looks at your ticket quickly, which saves time for honest passengers. The TTE on the train is the one whose decision counts. React is the platform check: fast, friendly and easy to skip. Django is the TTE: every request passes through it, from React, curl or anything else.
| Rule for a review | React (comfort) | Django (decides) |
|---|---|---|
| Rating is a whole number from 1 to 5 | A <select> with five options; "Choose a rating" if empty | IntegerField with min 1, max 5 from the model |
| Comment is at most 1,000 characters | maxLength and a live counter | CharField(max_length=1000) |
| One review per user per book | Cannot know for sure | UniqueTogetherValidator and the database constraint |
| Only logged-in users may post | Hides the form (next lesson) | IsAuthenticatedOrReadOnly returns 403 |
Look at the third row. React cannot reliably know that Kabir already reviewed a book; another tab may have posted a second ago. Some rules can only be checked on the server. So the form must be ready to show any error Django sends, not only the ones React expects.
Step 1: put the length rule on the server first
Start with the rule that counts. Add a comment field to ReviewSerializer in books/serializers.py:
class ReviewSerializer(serializers.ModelSerializer):
user = serializers.HiddenField(default=serializers.CurrentUserDefault())
username = serializers.CharField(source="user.username", read_only=True)
comment = serializers.CharField(max_length=1000, allow_blank=True, required=False)
# class Meta stays the sameThe model's TextField has no length limit, so without this line a script could post a 5 MB comment. Test it as Kabir with the cookie jar from Authentication: Sessions vs JWT, once with a 1,001-character comment and once with an empty rating:
LONG=$(python -c "print('a' * 1001)")
curl -c jar.txt -b jar.txt -X POST http://127.0.0.1:8000/api/reviews/ -H "Content-Type: application/json" -H "X-CSRFToken: $TOKEN" -d "{\"book\": 2, \"rating\": 4, \"comment\": \"$LONG\"}"
curl -c jar.txt -b jar.txt -X POST http://127.0.0.1:8000/api/reviews/ -H "Content-Type: application/json" -H "X-CSRFToken: $TOKEN" -d '{"book": 2, "rating": "", "comment": "x"}'{"comment":["Ensure this field has no more than 1000 characters."]}
{"rating":["A valid integer is required."]}Both came back with status 400. Now the server is safe, and React can add comfort on top.
Step 2: one helper for every error shape
You have met three error bodies from DRF: field errors ({"rating": [...]}), non_field_errors and a single detail. A network failure has no body at all. Create src/utils/errors.js to sort any of them into two piles: messages for a field the form shows, and messages for the whole form.
// Turn an apiFetch error into messages for each field and messages for the whole form.
export function splitErrors(error, fieldNames) {
const data = error.data;
if (error.status === undefined || error.status >= 500) {
return { fields: {}, form: ["The server is not answering right now. Please try again."] };
}
if (!data || typeof data.detail === "string") {
return { fields: {}, form: [error.message] }; // 403, 404, 429...
}
const fields = {};
const form = [];
for (const [name, messages] of Object.entries(data)) {
const list = Array.isArray(messages) ? messages.map(String) : [String(messages)];
if (fieldNames.includes(name)) fields[name] = list;
else form.push(...list); // non_field_errors, or a field this form does not show
}
return { fields, form };
}The last line matters more than it looks. If Django complains about a field the form has no box for, such as book, the message still reaches the user at the top instead of disappearing. Here is the helper working on the real bodies BookShelf returned in this course:
import { createRoot } from "react-dom/client";
function splitErrors(error, fieldNames) {
const data = error.data;
if (error.status === undefined || error.status >= 500) {
return { fields: {}, form: ["The server is not answering right now. Please try again."] };
}
if (!data || typeof data.detail === "string") return { fields: {}, form: [error.message] };
const fields = {};
const form = [];
for (const [name, messages] of Object.entries(data)) {
const list = Array.isArray(messages) ? messages.map(String) : [String(messages)];
if (fieldNames.includes(name)) fields[name] = list;
else form.push(...list);
}
return { fields, form };
}
// Real answers from the API (data) as apiFetch throws them
const cases = [
{ status: 400, data: { comment: ["Ensure this field has no more than 1000 characters."] } },
{ status: 400, data: { non_field_errors: ["The fields book, user must make a unique set."] } },
{ status: 400, data: { book: ['Invalid pk "99" - object does not exist.'], rating: ["Ensure this value is less than or equal to 5."] } },
{ status: 403, data: { detail: "Authentication credentials were not provided." }, message: "Authentication credentials were not provided." },
{ status: undefined, data: undefined, message: "Failed to fetch" },
];
createRoot(document.getElementById("root")).render(
<table border="1" cellPadding="4">
<thead><tr><th>Status</th><th>Field messages</th><th>Form messages</th></tr></thead>
<tbody>
{cases.map((c, i) => {
const { fields, form } = splitErrors(c, ["rating", "comment"]);
return (
<tr key={i}>
<td>{String(c.status)}</td>
<td><code>{JSON.stringify(fields)}</code></td>
<td>{form.join(" | ")}</td>
</tr>
);
})}
</tbody>
</table>
);The third row shows the rating message as a field message, while the book message moves to the form pile. The network failure becomes the calm server sentence.
Step 3: a field error component
Create src/components/FieldError.jsx:
export default function FieldError({ id, messages }) {
if (!messages?.length) return null;
return (
<p id={id} className="field-error">
{messages.join(" ")}
</p>
);
}Each input will point to its error with aria-describedby, and set aria-invalid when there is a problem. Screen readers then read "Rating, invalid entry, Choose a rating from 1 to 5" instead of a box that is only red. Colour alone is never enough.
Step 4: the review form
Create src/components/ReviewForm.jsx:
import { useState } from "react";
import { apiFetch } from "../api/client.js";
import { splitErrors } from "../utils/errors.js";
import FieldError from "./FieldError.jsx";
const MAX_COMMENT = 1000; // same limit as ReviewSerializer
const EMPTY_FORM = { rating: "", comment: "" };
const NO_ERRORS = { fields: {}, form: [] };
const LABELS = { 5: "Loved it", 4: "Liked it", 3: "It was fine", 2: "Not for me", 1: "Did not finish" };
// Quick checks for comfort. Django checks everything again.
function checkReview(values) {
const fields = {};
if (!values.rating) fields.rating = ["Choose a rating from 1 to 5."];
if (values.comment.length > MAX_COMMENT) fields.comment = [`Keep it under ${MAX_COMMENT} characters.`];
return fields;
}
export default function ReviewForm({ bookId, onSaved }) {
const [values, setValues] = useState(EMPTY_FORM);
const [errors, setErrors] = useState(NO_ERRORS);
const [saving, setSaving] = useState(false);
function handleChange(event) {
const { name, value } = event.target;
setValues({ ...values, [name]: value });
}
async function handleSubmit(event) {
event.preventDefault();
const local = checkReview(values);
if (Object.keys(local).length > 0) {
setErrors({ fields: local, form: [] });
return; // no request for mistakes we can see already
}
setSaving(true);
try {
const review = await apiFetch("/reviews/", {
method: "POST",
body: JSON.stringify({ book: Number(bookId), rating: Number(values.rating), comment: values.comment }),
});
setValues(EMPTY_FORM);
setErrors(NO_ERRORS);
onSaved(review);
} catch (error) {
setErrors(splitErrors(error, ["rating", "comment"]));
} finally {
setSaving(false);
}
}
return (
<form className="review-form" onSubmit={handleSubmit} noValidate>
<h2>Write a review</h2>
{errors.form.length > 0 && (
<div role="alert" className="form-errors">
{errors.form.map((message) => (
<p key={message}>{message}</p>
))}
</div>
)}
<label htmlFor="rating">Rating</label>
<select id="rating" name="rating" value={values.rating} onChange={handleChange}
aria-invalid={Boolean(errors.fields.rating)} aria-describedby="rating-error">
<option value="">Choose...</option>
{[5, 4, 3, 2, 1].map((n) => (
<option key={n} value={n}>
{n} - {LABELS[n]}
</option>
))}
</select>
<FieldError id="rating-error" messages={errors.fields.rating} />
<label htmlFor="comment">Comment (optional)</label>
<textarea id="comment" name="comment" rows={4} maxLength={MAX_COMMENT} value={values.comment}
onChange={handleChange} aria-invalid={Boolean(errors.fields.comment)}
aria-describedby="comment-count comment-error" />
<p id="comment-count" className="muted">
{values.comment.length} / {MAX_COMMENT}
</p>
<FieldError id="comment-error" messages={errors.fields.comment} />
<button type="submit" disabled={saving}>
{saving ? "Saving..." : "Post review"}
</button>
</form>
);
}The important decisions:
- Controlled inputs. Both fields read from
valuesand write back through onehandleChange, which uses each input'sname. noValidateturns off the browser's own pop-up bubbles, so every message comes from our code and looks the same. We still usemaxLength, which simply stops typing at 1,000.- Numbers are sent as numbers. A
<select>always gives strings, soNumber()turns"4"into4. DRF would accept"4"too, but the contract says integer. savingblocks double submits. On a slow 3G connection in a small town, people press the button again. The disabled button and its "Saving..." text stop the second request.- Errors are replaced, not merged. Each submit starts fresh, so an old message never sits next to a fixed field.
Step 5: show it on the book page
In BookDetail.jsx, import the form and place it after the review list. After a save, reload both requests: the reviews list gets the new review and the book gets its new average.
<ReviewForm
bookId={bookId}
onSaved={() => {
reviews.reload(); // show the new review
book.reload(); // and the new average
}}
/>Step 6: try it in the browser
There is no login screen until the next lesson. To test as Kabir today, open the browser's developer console on http://localhost:5173 and run this once (use his real password). It does what apiFetch does: fetch the CSRF cookie, then post the login with the token.
await fetch("/api/auth/csrf/");
const token = document.cookie.match(/csrftoken=([^;]+)/)[1];
await fetch("/api/auth/login/", {
method: "POST",
headers: { "Content-Type": "application/json", "X-CSRFToken": token },
body: JSON.stringify({ username: "kabir", password: "HIS-PASSWORD" }),
});We ran the whole sequence in headless Chrome on /books/2 (Malgudi Days) and read the form's text after each step. Here is what each step showed:
1. Post review with nothing chosen: Choose a rating from 1 to 5.
2. Rating 4, comment typed, not logged in: Authentication credentials were not provided.
3. After the console login, Post review: the form empties and the page shows
R. K. Narayan, 1943. 4.0 from 1 review
kabir (4/5, 16 Nov 2026) Every story feels like a walk through a small town near Mysuru.
4. On /books/1, which Kabir already reviewed, rating 3:
The fields book, user must make a unique set.Step 1 sent no request at all. Step 2 reached Django, and the 403 detail appeared at the top of the form. Step 4 is the rule only the server could check. The message is DRF's own wording; Login, Protected Routes & Sessions hides the form for books you have already reviewed, so most readers never see it.
You can try the same form here, against a fake API with the same rules and messages and a short delay so you can watch the button change:
import { useState } from "react";
import { createRoot } from "react-dom/client";
// Stand-in for POST /api/reviews/ with BookShelf's rules and exact messages
function fakeApi(body, loggedIn) {
return new Promise((resolve, reject) => setTimeout(() => {
const fail = (status, data, message) => reject(Object.assign(new Error(message), { status, data }));
if (!loggedIn) return fail(403, { detail: "Authentication credentials were not provided." }, "Authentication credentials were not provided.");
if (body.comment.length > 1000) return fail(400, { comment: ["Ensure this field has no more than 1000 characters."] }, "Request failed with status 400");
if (body.book === 1) return fail(400, { non_field_errors: ["The fields book, user must make a unique set."] }, "Request failed with status 400");
resolve({ id: 9, ...body, username: "kabir" });
}, 700));
}
function splitErrors(error, fieldNames) {
if (!error.data || typeof error.data.detail === "string") return { fields: {}, form: [error.message] };
const fields = {};
const form = [];
for (const [name, list] of Object.entries(error.data)) {
if (fieldNames.includes(name)) fields[name] = list;
else form.push(...list);
}
return { fields, form };
}
function ReviewForm({ bookId, loggedIn }) {
const [values, setValues] = useState({ rating: "", comment: "" });
const [errors, setErrors] = useState({ fields: {}, form: [] });
const [saving, setSaving] = useState(false);
const [saved, setSaved] = useState(null);
async function handleSubmit(event) {
event.preventDefault();
if (!values.rating) return setErrors({ fields: { rating: ["Choose a rating from 1 to 5."] }, form: [] });
setSaving(true);
try {
setSaved(await fakeApi({ book: bookId, rating: Number(values.rating), comment: values.comment }, loggedIn));
setValues({ rating: "", comment: "" });
setErrors({ fields: {}, form: [] });
} catch (error) {
setErrors(splitErrors(error, ["rating", "comment"]));
} finally {
setSaving(false);
}
}
const red = { color: "#b00020", margin: 0 };
return (
<form onSubmit={handleSubmit} noValidate style={{ display: "grid", gap: 4, maxWidth: 360 }}>
{errors.form.map((m) => <p key={m} role="alert" style={red}>{m}</p>)}
<label htmlFor="rating">Rating</label>
<select id="rating" value={values.rating} onChange={(e) => setValues({ ...values, rating: e.target.value })}>
<option value="">Choose...</option>
{[5, 4, 3, 2, 1].map((n) => <option key={n} value={n}>{n}</option>)}
</select>
{errors.fields.rating && <p style={red}>{errors.fields.rating.join(" ")}</p>}
<label htmlFor="comment">Comment ({values.comment.length} / 1000)</label>
<textarea id="comment" value={values.comment} onChange={(e) => setValues({ ...values, comment: e.target.value })} />
{errors.fields.comment && <p style={red}>{errors.fields.comment.join(" ")}</p>}
<button type="submit" disabled={saving}>{saving ? "Saving..." : "Post review"}</button>
{saved && <p>Saved review {saved.id}: {saved.rating}/5 by {saved.username}</p>}
</form>
);
}
function Demo() {
const [bookId, setBookId] = useState(2);
const [loggedIn, setLoggedIn] = useState(true);
return (
<main>
<label><input type="checkbox" checked={loggedIn} onChange={(e) => setLoggedIn(e.target.checked)} /> Logged in</label>{" "}
<select value={bookId} onChange={(e) => setBookId(Number(e.target.value))} aria-label="Book">
<option value={2}>Malgudi Days (not reviewed yet)</option>
<option value={1}>Swami and Friends (already reviewed)</option>
</select>
<ReviewForm key={bookId} bookId={bookId} loggedIn={loggedIn} />
</main>
);
}
createRoot(document.getElementById("root")).render(<Demo />);This editor version has no maxLength, so you can paste more than 1,000 characters and see the server-style message. Untick "Logged in" for the 403, or pick Swami and Friends for the duplicate.
Common mistakes
- Validating only in React. A curl request skips your form. Every rule must exist in the serializer or model.
- Showing only field errors.
non_field_errorsanddetailmessages vanish unless the form has a place for them. - Dropping errors for fields the form does not show. Send them to the form-level list.
- No pending state. Double clicks create duplicate requests; disable the button while saving.
- Red borders as the only signal. Add text,
aria-invalidandaria-describedby.
Interview questions
1. Why validate in React at all if Django validates everything?
For speed and comfort. Simple checks such as an empty required field give instant feedback without a network round trip. They are optional extras; the server's checks are the ones that protect the data.
2. Which validation rules can only run on the server?
Rules that need the database or other users' actions: uniqueness (one review per book), whether a related object exists, permissions, and limits that change. React may guess, but another request could change the answer a moment later.
3. How do you map DRF validation errors to a React form?
DRF returns an object keyed by field name with lists of messages, plus non_field_errors or a single detail. Put messages for known fields next to those inputs, and show everything else in a form-level alert, so no message is lost.
4. How do you prevent duplicate submissions?
Keep a saving flag, disable the submit button while a request is running, and enforce uniqueness on the server as well, with a constraint, because a second tab can still submit.
Key points
- React checks are for comfort; the serializer and database are the real rules.
- Put the server rule in place first (
max_length=1000), then mirror it in React. splitErrors()turns field errors,non_field_errors,detailand network failures into field and form messages.- Show field errors next to inputs with
aria-invalidandaria-describedby, and form errors in arole="alert"box. - Disable the submit button while saving, send numbers as numbers, and reload related data after success.
Exercise
Let Kabir edit his own review. On the book page, show an "Edit" button next to his review. It opens the same kind of form, filled with his current rating and comment, and saves with PATCH /api/reviews/<id>/, sending only the fields that changed. Show Django's errors with splitErrors(). Test it by changing the comment of his Swami and Friends review.
Show solution
// src/components/EditReviewForm.jsx
import { useState } from "react";
import { apiFetch } from "../api/client.js";
import { splitErrors } from "../utils/errors.js";
import FieldError from "./FieldError.jsx";
export default function EditReviewForm({ review, onSaved, onCancel }) {
const [values, setValues] = useState({ rating: String(review.rating), comment: review.comment });
const [errors, setErrors] = useState({ fields: {}, form: [] });
const [saving, setSaving] = useState(false);
async function handleSubmit(event) {
event.preventDefault();
const changes = {};
if (Number(values.rating) !== review.rating) changes.rating = Number(values.rating);
if (values.comment !== review.comment) changes.comment = values.comment;
if (Object.keys(changes).length === 0) return onCancel();
setSaving(true);
try {
onSaved(await apiFetch(`/reviews/${review.id}/`, { method: "PATCH", body: JSON.stringify(changes) }));
} catch (error) {
setErrors(splitErrors(error, ["rating", "comment"]));
} finally {
setSaving(false);
}
}
const change = (e) => setValues({ ...values, [e.target.name]: e.target.value });
return (
<form onSubmit={handleSubmit} noValidate>
{errors.form.length > 0 && <p role="alert">{errors.form.join(" ")}</p>}
<select name="rating" value={values.rating} onChange={change} aria-label="Rating">
{[5, 4, 3, 2, 1].map((n) => <option key={n} value={n}>{n}</option>)}
</select>
<FieldError messages={errors.fields.rating} />
<textarea name="comment" maxLength={1000} value={values.comment} onChange={change} aria-label="Comment" />
<FieldError messages={errors.fields.comment} />
<button type="submit" disabled={saving}>Save</button>{" "}
<button type="button" onClick={onCancel}>Cancel</button>
</form>
);
}In BookDetail, keep an editingId in state and render EditReviewForm in place of the review whose id matches, with onSaved={() => { setEditingId(null); reviews.reload(); book.reload(); }}. PATCH with only the changed fields keeps the request small, and IsReviewerOrReadOnly still stops anyone editing someone else's review, whatever the button says.
Quick Quiz
1. Which check must exist on the server, even if React already does it?
The browser is not trusted; curl and scripts never run your form code.
2. Where should a non_field_errors message appear?
It is not about one field, so it belongs to the whole form.
3. Why is the submit button disabled while saving is true?
A pending state blocks repeat submissions on slow connections.
4. Django returns {"book": ["Invalid pk \"99\" - object does not exist."]} but the form has no book field. What does splitErrors do with it?
Unknown fields go to the form pile, so the user still sees the message.
Learn Django + React with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
