Laravel Advance | Laravel custom validation rules example
Validation is a primary requirement of every project, without validation we can not release successful applications or websites. Because if you haven’t implemented validation then you get wrong information from user input. Laravel provides there are several default validation rules like required, max, min, array, unique, digits, in, boolean, before, after, etc. We can simply use those validation rules in the laravel application. But if you require to create your own custom validation like given value should be in uppercase or lowercase etc as we require.
Here, I will simply represent how to make custom validator rules in the laravel application and it is very simple, so you have to just follow bellow step, make sure you can create only for laravel , if you want to create on laravel then you can follow this tutorial.
So let’s follow the below step, I make an example from scratch. In this example, I take the number text field and you can just enter an even number, If you enter an odd number then you got a validation error.
Step 1: Create Custom Validation Rule
In the first step, we will create custom validation rules by running the following command. Bellow command through you can create Validation rules file and we can write logic on that file. So let’s run the below command.
php artisan make:rule CheckOddEvenRule
Ok, after successfully running the above command, you will find new “rules” folder in the app directory. In the rules folder you will also find the CheckOddEvenRule.php file. We have to simply write logic there, if you enter an even number then return true otherwise don’t do anything.
So, you should have files like as below
app/Rules/CheckOddEvenRule.php
<?phpnamespace App\Rules;use Illuminate\Contracts\Validation\Rule;class CheckOddEvenRule implements Rule{/*** Create a new rule instance.** @return void*/public function __construct(){}/*** Determine if the validation rule passes.** @param string $attribute* @param mixed $value* @return bool*/public function passes($attribute, $value){if($value%2 == 0){return true;}}/*** Get the validation error message.** @return string*/public function message(){return 'The :attribute must be even value.';}}
Step 2: Add Routes
Here, we need to add two routes for create form get method and another for post method. so open your routes/web.php file and add following route.
routes/web.php
Route::get("form","FormController@index");Route::post("form","FormController@store");
Step 3: Create FormController
Here, now we should create a new controller as FormController. So run the below command and create a new controller. bellow controller for creating a controller.
php artisan make:controller FormController
After the below command, you will find a new file in this path app/Http/Controllers/FormController.php.
This controller will create seven methods by default as below methods:
1)index()
2)store()
So, let’s copy below code and put it on the FormController.php file.
app/Http/Controllers/FormController.php
<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;use App\Rules\CheckOddEvenRule;class FormController extends Controller{/*** Display a listing of the resource.** @return \Illuminate\Http\Response*/public function index(){return view('myForm');}/*** Display a listing of the resource.** @return \Illuminate\Http\Response*/public function store(){$input = request()->validate(['name' => 'required','number' => ['required',new CheckOddEvenRule()]]);dd("You can proceed now...");}}
Step 4: Create View File
Finally, at the end of this example, we have to create myForm.blade.php file, in this file, we will create a form and display validation error so let’s create myForm.blade.php file and put bellow code
resources/views/myForm.blade.php
<!DOCTYPE html><html><head><title>Laravel 5.5 custom validation rules example</title><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1"><link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"></head><body><div class="container"><h1>Laravel 5.5 custom validation rules example</h1><form method="POST" action="{{ url('form') }}">{{ csrf_field() }}<div class="form-group"><label>Name:</label><input type="text" name="name" class="form-control" placeholder="Name">@if ($errors->has('name'))<span class="text-danger">{{ $errors->first('name') }}</span>@endif</div><div class="form-group"><label>Number:</label><input type="number" name="number" class="form-control" placeholder="Number">@if ($errors->has('number'))<span class="text-danger">{{ $errors->first('number') }}</span>@endif</div><div class="form-group"><button class="btn btn-success btn-submit">Submit</button></div></form></div></body></html>
Now we are ready to run our custom validation rules example so run bellow command for quick run
php artisan serve
Now you can open bellow URL on your browser
http://localhost:8000/form