In this episode, we jump into form validation in Livewire 3. We start by noticing that, right now, we're just letting any value (including blanks!) get submitted when we try to create a book. Not ideal. So, we're going to fix that.
The cool thing about Livewire 3 is that you can use PHP attributes directly on your form properties to define validation rules. It's pretty clean: you just pop an attribute with your rules above your properties like title
and author
. But, there's a catch—a rule alone doesn't run the validation for you. You need to actually call the validate()
method when your form is submitted to enforce those rules.
After wiring up validation, we test it out. When you hit submit with empty fields, nothing gets created—nice! Next, we cover how to display validation messages. This is done the same way as in regular Laravel/Blade, using the @error
directive, but referencing the proper form properties.
We then dive into customizing those error messages. You can do it with a messages()
method in your component, or even better, you can define custom messages (and display names) right in the rule attribute itself for each property—super handy!
Finally, we touch on multiple validation rules for a field. Just stack them up on separate lines, and you can even customize each rule's output as needed.
So by the end, you've got slick, customizable validation using all the power of Livewire 3's new syntax—ready to keep your forms squeaky clean!