Laravel Create a Custom Form Validation Rule for Beginners
So in this post, you’ll learn to create a custom validation rule in Laravel and the first thing to start is by creating a Rule using the below command.
php artisan make:rule ValidUsername
This command will create a file under App\Rules and contains two methods they are passes()
and message
.
- passes(): This method will check the value on conditions and return the boolean value.
- message(): This method will return the message if the method
passes()
returnfalse
.
In app\Rules\ValidUsername.php
<?php namespace App\Rules; use Illuminate\Contracts\Validation\Rule; class ValidUsername implements Rule { /** * Determine if the validation rule passes. * * @param string $attribute * @param mixed $value * @return bool */ public function passes($attribute, $value) { //this condition checks wheather the username contains any empty spaces or quotes return ( preg_match( '/[\'"\s]/', $value ) )? false : true; } /** * Get the validation error message. * * @return string */ public function message() { return 'The Username must not contain any spaces and special characters such as single and double quotes'; } }
Call Validator::make() method in controller
Now to use ValidUsername
the rule just call it with new ValidUsername
and no brackets.
In app\Http\Controllers\HomeController.php
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Rules\ValidUsername; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; class HomeController extends Controller { public function home(){ $input = [ 'username' => "sam 123" ]; $rules = [ 'username' => ['required', new ValidUsername ] ]; $validator = Validator::make( $input, $rules ); dump( "Is valid : ".$validator->fails() ); dump( $validator->errors() ); } }
Create a Web Route
In routes\web.php.
<?php use App\Http\Controllers\HomeController; use Illuminate\Support\Facades\Route; Route::get( 'validation/home', [ HomeController::class, 'home' ] );
Output

Laravel Custom Validation Rule to Validate Username Output
Watch Video
Extra Tips
Insisted of creating a new rule you can pass a function as a rule which calls a $fail
closure.
// from this $rules = [ 'username' => ['required', new ValidUsername ] ]; // to this $rules = [ 'username' => [ 'required', function ($attribute, $value, $fail) { if ( preg_match( '/[\'"\s]/', $value ) ) { $fail( "The Username must not contain any spaces and special characters such as single and double quotes" ); } }, ] ];
Conclusion
So we have reached the end of our post on Laravel Create a Custom Form Validation Rule for Beginners. Support us by sharing this post.
Related Posts
- Demystifying Laravel Model Listeners and Observers for Beginners
- Laravel Google Drive API – The Best way to take a full backup of your app




