LoginSignup
1
1

More than 1 year has passed since last update.

【Laravel】AppServiceProviderにカスタムバリデーションを登録する。

Last updated at Posted at 2022-03-17

自分用のメモとして残します。

AppServiceProviderのboot内に定義することで、暗黙的にインクルードされる。
そのため、フォームリクエスト内やコントローラ内でバリデーションで直ぐに使える。

やり方

AppServiceProviderに任意のバリデーションルールValidator::extendで定義する。
下記の例は入力値を半角全角のカタカナ英数字を正規表現で判定します。
katakana_or_number_or_abc 呼び出せる。

app\Providers\AppServiceProvider.php
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

use Illuminate\Support\Facades\Validator;


class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {

        Validator::extend('katakana_or_number_or_abc', function ($attribute, $value, $parameters, $validator) {
            $arr_regex= [
                '\-',//半角ハイフン
                'ー',//全角ハイフン
                '0-9' ,// 半角数字
                '0-9' ,//全角数字
                'a-z' ,//全角英字(小文字)
                'A-Z' ,//全角英字(大文字)
                'a-z' ,//半角英字(小文字)
                'A-Z' ,//半角英字(大文字)
                'ァ-ヴ',// 全角カタカナ
                'ヲ-゚' ,// 半角カタカナ
            ];
            $regex = '/^['.join('',$arr_regex).']+$/u';

            return preg_match($regex, $value);
        }, ':attributeはカナと英数字のみで入力してください。');

    }
}

以上です。

1
1
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
1
1