1
0

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 3 years have passed since last update.

バリデーション 項目ごとにエラー文を表示させる

Posted at

今日の勉強

バリデーションでエラー文を表示させる。
入力項目が複数ある時に
エラーがあった項目にそれぞれ
エラー文を表示させる

ちなみに
PHPフレームワーク Laravel入門
をもとに学習を進めていく。

index.blade.php
   @if (count($errors) > 0)
   <p>エラー</p>
   @endif

この count が一体何者なのかわからなかったので調べた。
count()の変数の中に要素が何個入っているかカウントしれくれる。
つまり$errorsのなかに1つでも値が入っていたら( > 0)
「エラー!」を表示してね。という処理。
バリデーションでエラーが確認されたら
$errors(という箱?)に保管されるので
一つでもエラーが確認されたら
エラー文が表示される。

index.blade.php
   <form action="/hello" method="post">
   <table>
      @csrf
      @if ($errors->has('name'))
      <tr><th>エラー</th><td>{{$errors->first('name')}}</td></tr>
      @endif
      <tr><th>名前: </th><td><input type="text" name="name" value="{{old('name')}}"</td></tr>
  .
  .
  .
  .

has()はエラーメッセージを持っているかチェックしてくれる。

以下参考ページ
入門者のためのLaravelのバリデーションとエラーメッセージ

エラーが発生した場合は
$errors->first()のという値を出力
firstは()の中の最初のエラーメッセージを取得する。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?