5
4

More than 1 year has passed since last update.

Laravelで日本語のバリデーションを設定する。

Posted at

View

①各フォームごとにエラーメッセージを表示する。

スクリーンショット 2021-09-10 16.33.04.png

blade.php
<label for="exampleFormControlTextarea1">郵便番号</label>
<p class="card-text">
    <input id="zipCode" type="text" name="zipCode" class="@error('zipCode') is-invalid @enderror" placeholder="※ハイフンなし" value="{{ old('zipCode') }}"  autocomplete="zipCode" autofocus>

    @error('zipCode')
     <span class="invalid-feedback" role="alert">
         <strong>{{ $message }}</strong>
     </span>
    @enderror

</p>

仕組みを解説


//バリデーションエラーに id='zipCode'のinputタグが引っかかっていた場合、
class="@error('zipCode') is-invalid @enderror"
:
:
//⬇この記述を発火させて、エラー文を表示する。
 @error('zipCode')
  <span class="invalid-feedback" role="alert">
      <strong>{{ $message }}</strong>
  </span>
 @enderror

②メッセージを全て一箇所に展開する。

スクリーンショット 2021-09-10 16.32.57.png

blade.php
@if ($errors->any())
    <ul class="border border-red-400 bg-red-100 px-4 py-3 text-red-700 mb-10 w-4/5 m-auto">
    @foreach ($errors->all() as $error)
        <li style="color: red; font-size: 14px">{{$error}}</li>
    @endforeach
    </ul>
@endif

バリデーションメッセージの日本語化

日本語の設定にする。

config/app.php.php
    'locale' => 'ja',

ファイルをコピー

resources/lang

enフォルダと、ファイルが4つ入っている。
→まるごとコピーして、jaフォルダに名前を変える。

resources/lang/ja/auth.php
resources/lang/ja/pagination.php
resources/lang/ja/passwords.php
resources/lang/ja/validation.php

以下のPHPファイルに、まるごと日本語メッセージをコピペする。

/validation.php

日本語訳されたvalidation.php

validation.php
<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Validation Language Lines
    |--------------------------------------------------------------------------
    |
    | The following language lines contain the default error messages used by
    | the validator class. Some of these rules have multiple versions such
    | as the size rules. Feel free to tweak each of these messages here.
    |
    */

    'accepted'        => ':attributeを承認してください。',
    'active_url'      => ':attributeは、有効なURLではありません。',
    'after'           => ':attributeには、:dateより後の日付を指定してください。',
    'after_or_equal'  => ':attributeには、:date以降の日付を指定してください。',
    'alpha'           => ':attributeには、アルファベッドのみ使用できます。',
    'alpha_dash'      => ":attributeには、英数字('A-Z','a-z','0-9')とハイフンと下線('-','_')が使用できます。",
    'alpha_num'       => ":attributeには、英数字('A-Z','a-z','0-9')が使用できます。",
    'array'           => ':attributeには、配列を指定してください。',
    'before'          => ':attributeには、:dateより前の日付を指定してください。',
    'before_or_equal' => ':attributeには、:date以前の日付を指定してください。',
    'between'         => [
        'numeric' => ':attributeには、:minから、:maxまでの数字を指定してください。',
        'file'    => ':attributeには、:min KBから:max KBまでのサイズのファイルを指定してください。',
        'string'  => ':attributeは、:min文字から:max文字にしてください。',
        'array'   => ':attributeの項目は、:min個から:max個にしてください。',
    ],
    'boolean'              => ":attributeには、'true'か'false'を指定してください。",
    'confirmed'            => ':attributeと:attribute確認が一致しません。',
    'date'                 => ':attributeは、正しい日付ではありません。',
    'date_equals'          => ':attributeは:dateに等しい日付でなければなりません。',
    'date_format'          => ":attributeの形式は、':format'と合いません。",
    'different'            => ':attributeと:otherには、異なるものを指定してください。',
    'digits'               => ':attributeは、:digits桁にしてください。',
    'digits_between'       => ':attributeは、:min桁から:max桁にしてください。',
    'dimensions'           => ':attributeの画像サイズが無効です',
    'distinct'             => ':attributeの値が重複しています。',
    'email'                => ':attributeは、有効なメールアドレス形式で指定してください。',
    'ends_with'            => 'The :attribute must end with one of the following: :values',
    'exists'               => '選択された:attributeは、有効ではありません。',
    'file'                 => ':attributeはファイルでなければいけません。',
    'filled'               => ':attributeは必須です。',
    'gt'                   => [
        'numeric' => ':attributeは、:valueより大きくなければなりません。',
        'file'    => ':attributeは、:value KBより大きくなければなりません。',
        'string'  => ':attributeは、:value文字より大きくなければなりません。',
        'array'   => ':attributeの項目数は、:value個より大きくなければなりません。',
    ],
    'gte'                  => [
        'numeric' => ':attributeは、:value以上でなければなりません。',
        'file'    => ':attributeは、:value KB以上でなければなりません。',
        'string'  => ':attributeは、:value文字以上でなければなりません。',
        'array'   => ':attributeの項目数は、:value個以上でなければなりません。',
    ],
    'image'                => ':attributeには、画像を指定してください。',
    'in'                   => '選択された:attributeは、有効ではありません。',
    'in_array'             => ':attributeが:otherに存在しません。',
    'integer'              => ':attributeには、整数を指定してください。',
    'ip'                   => ':attributeには、有効なIPアドレスを指定してください。',
    'ipv4'                 => ':attributeはIPv4アドレスを指定してください。',
    'ipv6'                 => ':attributeはIPv6アドレスを指定してください。',
    'json'                 => ':attributeには、有効なJSON文字列を指定してください。',
    'lt'                   => [
        'numeric' => ':attributeは、:valueより小さくなければなりません。',
        'file'    => ':attributeは、:value KBより小さくなければなりません。',
        'string'  => ':attributeは、:value文字より小さくなければなりません。',
        'array'   => ':attributeの項目数は、:value個より小さくなければなりません。',
    ],
    'lte'                  => [
        'numeric' => ':attributeは、:value以下でなければなりません。',
        'file'    => ':attributeは、:value KB以下でなければなりません。',
        'string'  => ':attributeは、:value文字以下でなければなりません。',
        'array'   => ':attributeの項目数は、:value個以下でなければなりません。',
    ],
    'max'                  => [
        'numeric' => ':attributeには、:max以下の数字を指定してください。',
        'file'    => ':attributeには、:max KB以下のファイルを指定してください。',
        'string'  => ':attributeは、:max文字以下にしてください。',
        'array'   => ':attributeの項目は、:max個以下にしてください。',
    ],
    'mimes'                => ':attributeには、:valuesタイプのファイルを指定してください。',
    'mimetypes'            => ':attributeには、:valuesタイプのファイルを指定してください。',
    'min'                  => [
        'numeric' => ':attributeには、:min以上の数字を指定してください。',
        'file'    => ':attributeには、:min KB以上のファイルを指定してください。',
        'string'  => ':attributeは、:min文字以上にしてください。',
        'array'   => ':attributeの項目は、:min個以上にしてください。',
    ],
    'not_in'               => '選択された:attributeは、有効ではありません。',
    'not_regex'            => ':attributeの形式が無効です。',
    'numeric'              => ':attributeには、数字を指定してください。',
    'password'             => ':attributeが間違っています',
    'present'              => ':attributeが存在している必要があります。',
    'regex'                => ':attributeには、有効な正規表現を指定してください。',
    'required'             => ':attributeは、必ず指定してください。',
    'required_if'          => ':otherが:valueの場合、:attributeを指定してください。',
    'required_unless'      => ':otherが:values以外の場合、:attributeを指定してください。',
    'required_with'        => ':valuesが指定されている場合、:attributeも指定してください。',
    'required_with_all'    => ':valuesが全て指定されている場合、:attributeも指定してください。',
    'required_without'     => ':valuesが指定されていない場合、:attributeを指定してください。',
    'required_without_all' => ':valuesが全て指定されていない場合、:attributeを指定してください。',
    'same'                 => ':attributeと:otherが一致しません。',
    'size'                 => [
        'numeric' => ':attributeには、:sizeを指定してください。',
        'file'    => ':attributeには、:size KBのファイルを指定してください。',
        'string'  => ':attributeは、:size文字にしてください。',
        'array'   => ':attributeの項目は、:size個にしてください。',
    ],
    'starts_with'          => ':attributeは、次のいずれかで始まる必要があります。:values',
    'string'               => ':attributeには、文字を指定してください。',
    'timezone'             => ':attributeには、有効なタイムゾーンを指定してください。',
    'unique'               => '指定の:attributeは既に使用されています。',
    'uploaded'             => ':attributeのアップロードに失敗しました。',
    'url'                  => ':attributeは、有効なURL形式で指定してください。',
    'uuid'                 => ':attributeは、有効なUUIDでなければなりません。',

    /*
    |--------------------------------------------------------------------------
    | Custom Validation Language Lines
    |--------------------------------------------------------------------------
    |
    | Here you may specify custom validation messages for attributes using the
    | convention "attribute.rule" to name the lines. This makes it quick to
    | specify a specific custom language line for a given attribute rule.
    |
    */

    'custom' => [
        'attribute-name' => [
            'rule-name' => 'custom-message',
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Custom Validation Attributes
    |--------------------------------------------------------------------------
    |
    | The following language lines are used to swap our attribute placeholder
    | with something more reader friendly such as "E-Mail Address" instead
    | of "email". This simply helps us make our message more expressive.
    |
    */
];

カラム名の日本語化を登録する。

validation.php
:
:
'attributes' => [
    'address1' => '市区町村',
    'address2' => '町名・番地',
    'address3' => 'ビル・マンション名',
    'password' => 'パスワード',
],

念の為、キャッシュをクリアしておく。

php artisan config:cache

バリデーションメッセージのカスタム

blade.php
$request->validate([
    'introduction' => ['required', 'between:1,5'],
    'companyName' => ['required', 'max:2'],
    'companyNameKana' => ['required', 'max:2'],
    'zipCode' => ['max:5'],
    'prefecture' => ['max:5'],
    'address1' => ['max:5'],
    'address2' => ['max:5'],
    :
    :
],[
    'introduction.between' => '自己紹介文は1文字から5文字までです。',
    'companyName.max' => '事業者名は50文字までです。',
    'companyNameKana.max' => '全角カナでの入力です。',
        'companyNameKana.required' => '必須だって言っているでしょう!!!'
]);

配列の1つ目では、デフォルトのメッセージしか表示されない。
でも、配列の2つ目に、各ルールごとのエラーに対するメッセージをカスタムすることが出来る。

formタグの属性

id属性

id="zipCode"

HTML的な属性。
後出てくるが、inputタグが、打ち込んだ内容を保持する時に、どのフォームかの識別をする時に指定する。

@errors('zipCode')
エラーがあるかどうかの判断も、idの値で行っている。
ここを、@errors('pref')などとした場合は、id=prefタグに対するエラーが表示される。

value="{{ old('zipCode') }}"

name属性

name="zipCode"

$request->zipCode=入力した内容

PHP的な属性。
Requestファサードに格納される時の連想配列のキー名。

type属性

hidden
画面上は表示されない隠しデータを指定する
text
一行テキストボックスを作成する(初期値)
search
検索テキストの入力欄を作成するHTML5から追加
tel
電話番号の入力欄を作成するHTML5から追加
url
URLの入力欄を作成するHTML5から追加
email
メールアドレスの入力欄を作成するHTML5から追加
password
パスワード入力欄を作成する
datetime
UTC(協定世界時)による日時の入力欄を作成するHTML5から追加
date
日付の入力欄を作成するHTML5から追加
month
月の入力欄を作成するHTML5から追加
week
週の入力欄を作成するHTML5から追加
time
時間の入力欄を作成するHTML5から追加
datetime-local
UTC(協定世界時)によらないローカル日時の入力欄を作成するHTML5から追加
number
数値の入力欄を作成するHTML5から追加
range
レンジの入力欄を作成するHTML5から追加
color
色の入力欄を作成するHTML5から追加
checkbox
チェックボックスを作成する
radio
ラジオボタンを作成する
file
サーバーへファイルを送信する
submit
送信ボタンを作成する
image
画像ボタンを作成する
reset
リセットボタンを作成する
button
汎用ボタンを作成する

autocomplete属性

autocomplete="zipCode"

zip過去に入力した内容が入力候補として表示されるようになる。

スクリーンショット 2021-09-10 16.01.05.png

autofocus属性

autofocus

値を持たない属性。
画面が表示した時に、どのフォームに打ち込むように選択されている状態のタグに書き込む。

スクリーンショット 2021-09-10 16.23.34.png

value属性

value="{{ old('zipCode') }}"

リダイレクトバックしたときなどに、一画面前に入力した内容がフォームに残っているようにするもの。
他にも初期値などを設定できる。
この時は、idを指定することで、値を保持できる。

例えば!
以下のように記述すれば、同ページ内のid='prefecture'のinputタグのさっき打った値がでてくる。

<input ~~ value="{{ old('prefecture') }}">

placeholder属性

placeholder="※ハイフンなし"

valueではないが、空のときに、薄い灰色の時で文字を置く。

5
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
5
4