0
0
Laravelframework~30 mins

Custom validation rules in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
Laravel Custom Validation Rules
📖 Scenario: You are building a simple Laravel form to register users. You want to ensure the username is unique and only contains letters and numbers.
🎯 Goal: Create a custom validation rule in Laravel that checks if a username contains only letters and numbers, then apply it to a form request.
📋 What You'll Learn
Create a custom validation rule class named AlphaNumOnly
Add a passes method that returns true only if the username contains letters and numbers
Add a message method that returns a custom error message
Use the custom rule in a form request validation for the username field
💡 Why This Matters
🌍 Real World
Custom validation rules help enforce specific business logic on user input beyond built-in rules, improving data quality and user experience.
💼 Career
Laravel developers often create custom validation rules to meet unique application requirements and maintain clean, reusable validation code.
Progress0 / 4 steps
1
Create the custom validation rule class
Create a Laravel custom validation rule class named AlphaNumOnly using the artisan command php artisan make:rule AlphaNumOnly.
Laravel
Need a hint?

Use the artisan command to create the rule class, then implement passes and message methods.

2
Add a form request class for user registration
Create a Laravel form request class named RegisterUserRequest using the artisan command php artisan make:request RegisterUserRequest.
Laravel
Need a hint?

Use the artisan command to create the form request class.

3
Add validation rules to the form request
In the RegisterUserRequest class, add a rules method that returns an array with the username field using the required, unique:users,username, and the custom AlphaNumOnly rule.
Laravel
Need a hint?

Return an array with the username key and the required validation rules including the custom rule.

4
Use the form request in the controller
In your UserController, update the store method to accept the RegisterUserRequest as a parameter and use it to validate the incoming request.
Laravel
Need a hint?

Use the form request as a parameter and call User::create with the validated data.