Laravel 5.5 custom validation rules example (ok)

https://www.itsolutionstuff.com/post/laravel-55-custom-validation-rules-exampleexample.html

Một ví dụ đã hoàn thành

C:\xampp\htdocs\reset\routes\web.php

<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
 */
use App\Http\Controllers\HomeController;
use App\Http\Controllers\FormController;
Route::get('/', function () {
  dd('Welcome to simple user route file.');
});
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::get("form",[FormController::class,'index'])->name('form.index');;
Route::post("form",[FormController::class,'store'])->name('form.store');;

C:\xampp\htdocs\reset\app\Http\Controllers\FormController.php

<?php
namespace App\Http\Controllers;
use App\Rules\CheckOddEvenRule;
use Illuminate\Http\Request;
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(Request $request) {
    $request->validate([
      'name'   => 'required',
      'number' => ['required', new CheckOddEvenRule()],
    ]);
    dd("You can proceed now...");
  }
}

C:\xampp\htdocs\reset\app\Http\Controllers\CheckOddEvenRule.php

<?php
namespace App\Http\Controllers;
class CheckOddEvenRule extends Controller {
  /**
   * 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.';
  }
}

C:\xampp\htdocs\reset\app\Rules\CheckOddEvenRule.php

<?php
namespace 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.';
  }
}

C:\xampp\htdocs\reset\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>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>

Laravel 5.5 custom validation rules example

Validation is a primary requirement of every project, without validation we can not release successful application or website. Because if you haven't implemented validation then you get wrong information from use input. Laravel provide there are several default validation rules like required, max, min, array, unique, digits, in, boolean, before, after etc. We can simple use those validation rules in laravel 5.5 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 simple represent how to make custom validator rules in laravel 5.5 application and it is very simple, so you have to just follow bellow step, make sure you can create only for laravel 5.5, if you want to create on laravel 5.3, or 5.2 then you can follow this tutorial Laravel 5 - Create Custom Validation Rules.

So let's follow bellow step, i make example from scratch. In this example i take number text field and you can just enter even number, If you enter odd number then you got validation error.

Step 1: Create Custom Validation Rule

In first step, we will create custom validation rules by run following command. Bellow command through you can create Validation rules file and we can write a logic on that file. So let's run bellow command.

php artisan make:rule CheckOddEvenRule

Ok, after successfully run above command, you will found new "rules" folder in app directory. In rules folder you will also found CheckOddEvenRule.php file. We have to simple write logic there, if you enter even number then return true otherwise don't do anything.

So, you should have file like as bellow:

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");

Read Also: How to create custom helper in Laravel?

Step 3: Create FormController

Here, now we should create new controller as FormController. So run bellow command and create new controller. bellow controller for create controller.

php artisan make:controller FormController

After bellow command you will find new file in this path app/Http/Controllers/FormController.php.

In this controller will create seven methods by default as bellow methods:

1)index()

2)store()

So, let's copy bellow code and put on 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 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:

Read Also: Custom User Log Activity in Laravel App Example

http://localhost:8000/form

I hope it can help you...

Watch Online Video:

Last updated