In this episode, we dive into how to create custom validation rules—specifically for checking whether an email address already exists in the database, which is super useful for things like user registration forms. We start out by seeing the default behavior where, if you try to register with an already used email address, you run into a messy SQL error, not a user-friendly message. That's not great! So, the goal is to give users proper validation feedback instead.
The process involves creating a new directory structure for your custom validation rules and exceptions, following the PSR-4 autoloading standard. We build a rule called ExistsInDatabase
, which extends the base rule from the validation library. We also set up a custom exception that provides a human-readable error message.
After the rule and exception structure is ready, we register our namespaces so that the validation library can recognize our new rules and exceptions. Then, we update the registration logic to apply the new rule, making sure to handle the logic for both "does exist" and "does NOT exist" scenarios depending on how the rule is used.
Finally, we implement the actual database check: we inject the table and column name, access our database via the service container, and perform a lookup for the supplied value. We test it out—entering an existing email now triggers our custom error, while new emails pass as expected.
By the end, you've learned how to make validation rules that aren't just limited to built-in checks, but can hook into your application's database or other services. This opens the door to much more advanced and user-friendly validation across your app!