In this episode, we dive into validating the email field on our account form during the checkout process. Sounds simple, but there are a few nuances to consider — mainly, whether the user is signed in or not.
First, we talk about showing the account details form only to guests (not signed-in users), using a guest directive to conditionally display the section. Then, we hook up Laravel Livewire's wire:model.defer
to our email input so that we don't send a request on every keystroke, only on submission. We do a quick test to make sure the data is flowing in the right direction.
Once the basics are set up, we jump into defining validation rules for the email. We want the email to be required, actually be an email, have a max length, and (importantly) be unique in the users table. This way, if someone tries to check out with an already-registered email address, we prompt them to sign in instead. We also customize the validation attribute names and override the unique-email error message for a better user experience.
The tricky part comes when a user is already signed in. We don't want the form to require the email field or throw a validation error in this case. Instead of complex validation logic, we just pre-fill the email if the user is signed in and hide the input. We also adjust the unique rule so that it ignores the email of the currently authenticated user, making sure validation doesn't falsely complain.
After testing out all these scenarios (signed in, signed out, unique vs. existing emails), we've got a robust solution that covers all bases. Wrapping up, we note that you might want to collect more guest details if needed, and tease what's coming next: validating the shipping form.
So, what seemed like a quick task actually had a few gotchas, but now our account details section is rock solid!