In this episode, we're diving into one of the most important aspects of working with forms: validation! We start by noticing that our comment store controller doesn't have any validation yet, so we add some basic validation to make sure the form's body field is required.
Once that's set up, we test what happens in the browser by trying to submit the form without any input. We take a look at the network tab to see exactly how Inertia handles validation errors. You'll notice that when validation fails, an errors
object containing our error messages appears in the props sent back to the page—just like you'd expect if you were working with traditional Blade templates.
Next, we see how easy it is to access and display these error messages in the UI. We add a quick check under our form's textarea, showing the relevant validation message dynamically if there are errors. This is super handy since these errors are attached directly to the form instance, making them easy to use anywhere in your page component.
We also briefly explore how errors are attached to the correct form, which is great if you have multiple forms on a single page. Plus, for edge cases, you can access errors globally through the special page
variable if you really need to.
By the end, we quickly style up the error message to make it stand out, and that's it—validation is working, and errors show up right where you need them! If forms felt confusing before, you should feel much more confident in handling validation and displaying errors in your app.