After this lesson you can reject invalid submitted titles on the server and save only an explicit accepted field. Validation turns untrusted request data into an application decision. It should happen before persistence and produce a response the caller can understand.
Read only the intended input
Add the following create method to Books. The class already inherits BaseController and the form helper is loaded before rendering errors. The fully qualified model name keeps the fragment clear even if you have not added a use statement.
public function create()
{
helper('form');
$data = ['title' => $this->request->getPost('title')];
if (! $this->validateData($data, ['title' => 'required|max_length[120]'])) {
return $this->response->setStatusCode(422)->setBody(
view('books/form', ['errors' => $this->validator->getErrors()])
);
}
(new \App\Models\BookModel())->insert(['title' => $data['title']]);
return redirect()->to('/books')->with('notice', 'Book added.');
}This method was linted and exercised over HTTP with the previous lesson's CSRF-protected route. A blank title with a valid token returned 422 and did not insert a book. A valid fictional title was inserted and redirected to the catalogue. The notice becomes visible after the flashdata lesson adds its display.
The rule length is the course's explicit title policy, not an externally measured limit. The required rule checks presence according to the validator's behavior, while max_length checks the permitted length. The starter's strict validation rules are important for unexpected input types. Do not silently turn an array into a string just to pass validation.
Validation is a decision, not a cleaning ritual
A validator accepts or rejects a proposed value. It does not make the value safe in every later context. A title containing angle brackets may be legitimate text and still needs escaping when rendered. Conversely, HTML escaping does not decide whether a title is missing or too long.
Normalizing data can be useful, but it is a separate choice. For example, trimming surrounding whitespace changes the submitted value. If you add normalization, define when it happens and validate the resulting value consistently. Do not claim a normalizer checks authorization or prevents every injection problem.
The explicit data array contains only title. We do not pass every submitted field into the model. This makes the write contract readable and complements the model's allowedFields boundary. If a future form adds a price, define its representation and rules before including it in persistence.
Respond without inventing success
The error branch returns the same form with escaped validation messages and status 422. It does not redirect away and lose all explanation. The success branch redirects after persistence. These are two distinct paths and both need checking.
The example focuses on expected validation failures. A real application must also decide how database failures are logged and presented. Do not report “Book added” after catching and ignoring every exception. The diagnostics lesson keeps internal detail out of the public response while preserving useful evidence.
A successful model call is not a permission decision. This local exercise remains a demonstration until a reviewed authorization boundary protects writes. Keeping that limitation visible is more honest than naming the controller AdminBooks and assuming the name provides security.
Test the rejection path deliberately
A useful validation check submits a blank value, an overlong string and an unexpected type in the isolated application. Verify both the response and the database effect. A page displaying an error while still inserting the invalid record would be a failed implementation.
The fetched official Validation guide documents validateData and rules. The official Model guide supports insert and allowed fields. Our HTTP verification used actual requests and generated CSRF tokens, rather than treating PHP lint as proof of request behavior.
If you preserve submitted input for convenience, escape it in the form's value attribute. Do not display a raw submitted title inside an error paragraph. Failure paths handle untrusted data too, and attackers do not need a successful insert to target unsafe error rendering.
Common mistakes
Trusting browser required allows direct HTTP clients to bypass rules. Passing all request fields hides the write contract. Escaping before validation confuses presentation with acceptance. Returning success despite a failed persistence operation misleads the user. Finally, checking only valid input leaves the most important rejection behavior untested.
Exercise
Trace a blank-title request with a valid CSRF token through the method. State the status, whether insert runs and how errors reach the template. Then explain why a nonblank title still needs output escaping after it is accepted.
Show an answer
Validation fails, the method returns the form with status 422 and insert is not reached. The validator's errors array is passed under errors and escaped by the template. Acceptance establishes the title policy, not its safety as HTML markup; the view must still render the accepted title as escaped text.
Previous lesson · Next lesson · Related: explicit routes · Related: security boundaries
Key points
- Construct the intended input array explicitly.
- Invalid titles return 422 before insert.
- Accepted text still needs contextual output escaping.