2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Laravel カスタムバリデーション導入

Last updated at Posted at 2020-01-22

はじめに

  • Laravel ではバリデーションの機能がある。
  • デフォルトでもそれなりに使えるけど、カスタムした方が使える時もままある
  • ちょっと分からなくて調べたりしたのでそれを記述する

前提

laravel のバージョン

$ php artisan -V
Laravel Framework 5.8.16

使いたい

①カスタムバリデーションの作成をする

  • Validation のクラスを作成する。
  • 今回は、場所はapp/Services/ に作成する
  • メソッド名は validateの後ろにオリジナルの名前。この名前がバリデーションの名前になる。
  • 下記のメソッドは、半角英数字とスペースを許可するってこと。多分。
app/Services/CustomValidator.php
<?php

namespace App\Services;

class CustomValidator extends \Illuminate\Validation\Validator
{
    public function validateAlphanumeric($attribute, $value)
    {
        return (preg_match("/^[a-z0-9 ]+$/i", $value));
    }
}

② 呼び出せるようにサービスプロパイダーで有効にする

  • クラスを作ったままだと呼べないので、サービスプロパイダーという場所に登録する
  • AppServiceProvider に登録を行う
app/ServiceProviders/AppServiceProvider.php
<?php

namespace App\ServiceProviders;

use Illuminate\Support\ServiceProvider;

use App\Services\CustomValidator;   // 自分で作成したValidationのクラス

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // 自分で作成した Validation のクラス
        \Validator::resolver(function($translator, $data, $rules, $messages) {
            return new CustomValidator($translator, $data, $rules, $messages);
        });
    }

③フォーム単位?で使いたい。

  • コントローラで呼び出せるように Request クラスを生成して、割り当てていく。
  • 下記のコマンドで app/Http/Requests/TestRequest.php を作成する
$ php artisan make:request TestRequest
  • 作成した Request クラスを編集して、バリデーションをはめてく
  • バリデーションの名前は validate を抜いた名前でスネークケースにした名前にする
app/Http/Requests/TestRequest.php
<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class TestRequest extends Request
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            // 自分で作成したカスタムバリデーションの名前を name = "test_box" の
            // テキストボックスに当てはめる
            'test_box' => 'alpha_numeric',   
        ];
    }
}
  • コントローラ側でも使えるようにしていく
app/Http/Controllers/TestControllers.php
<?php

namespace App\Http\Controllers\Test;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\Http\Request\TestRequest;   // 作成した Request のクラスを使う

class TestController extends Controller
{
    // 作成した Request クラスを使う
    public function showForm(TestRequest $request)
    {
        処理を色々省略
        return view('test.form');
    }
}

④バリデーションエラーの時のメッセージを多言語化

  • バリデーションのエラーメッセージを多言語化できる。
  • /resources/lang/ja の下に validation.php を作成で日本語ファイル
  • /resources/lang/en の下に validation.php を作成で英語ファイル
/resources/lang/ja/validation.php
<?php

return [

    'alpha_numeric'  => '半角英数字または半角スペース以外は登録できません',
];
2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?