LoginSignup
39
39

More than 5 years have passed since last update.

Laravel5.3 で超ラクにバリデーションしてエラーメッセージを変更する

Last updated at Posted at 2016-10-26

環境

  • CentOS 7
  • PHP 7
  • Laravel 5.3

バリデーション処理の実装

Controller.php
\Validator::make(
    ['email' => $request['email']],
    ['email' => 'required|email|max:128']
)->validate();
blade.php
<div class="form-group @if(!empty($errors->first('email'))) has-error @endif">
    <label for="email" class="col-md-2 control-label">メールアドレス</label>
    <div class="col-md-6">
      <input type="email" class="form-control" id="email" name="email" placeholder="example@email.com" value="{{ old('email') }}" required="required">
      <span class="help-block">{{$errors->first('email')}}</span>
    </div>
</div>

↑だけでバリデーションが行われ、エラーがあった際は、
image
のように前の画面に自動で遷移して、エラー出力ができる。

エラーメッセージの場所

resources/lang/en/validation.phpで定義されている。

resources/lang/en/validation.php
<?php
return [
    ...
    'email'                => 'The :attribute must be a valid email address.',
    'exists'               => 'The selected :attribute is invalid.',
    'file'                 => 'The :attribute must be a file.',
    ...

エラーメッセージを日本語にする

今のままだとエラーメッセージが英語なので、日本語に直す。

  1. config/app.php'locale' = >'en''locale' => 'ja'に変更
  2. 日本語版のエラーメッセージファイルを GitHubからDL する
  3. resources/lang/ja/ に格納(ディレクトリは作る)

そうするとエラーメッセージが日本語になる。
image

エラーメッセージの内容を変更する

emailは必須です。

だとユーザーに優しくないので変更する。
先ほど追加したvalidation.php'attributes'の欄を以下のように変更する。

resources/lang/ja/validation.php
'attributes' => [
    'email' => 'メールアドレス',
],

そうするとユーザーにも優しいエラーメッセージになる。
image

39
39
3

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