Showing only one validation message for my array of inputs









up vote
0
down vote

favorite












I have a form that has 10 inputs fields, I want to check if any of those input fields are empty. If they do are empty or have more than 2 characters I want to display only one error message. With my current code I show an error for each field that is empty. I don't want the user to see 10 error messages. I tried many other methods but doesn't seem to work.



I want the error message to say: 'Predictions can't be empty or have more than 2 characters'



The controller



 public function store(Request $request) max:2'
]);
try
collect($requestData)
->each(function ($match, $key)
Prediction::create([
'user_id' => auth()->id(),
'match_id' => $key,
'homeTeam' => $match['homeTeamName'],
'awayTeam' => $match['awayTeamName'],
'homeScore'=> $match['homeTeam'],
'awayScore'=> $match['awayTeam'],
'result' => false
]);
);
auth()->user()->participated = true;
auth()->user()->addPoint();
auth()->user()->save();

return redirect('/predictions')->with('success', 'Weekly prediction created, new predictions can be made every Tuesday!');

catch(Exception $e)
return view('error.error');





My messages.blade.php file



@if(count($errors) > 0)
@foreach($errors->all() as $error)
<div class="alert alert-red">
$error
</div>
@endforeach
@endif

@if(session('success'))
<div class="alert alert-green">
session('success')
</div>
@endif

@if(session('error'))
<div class="alert alert-danger">
session('error')
</div>
@endif


The view



@include('inc.messages')
!! Form::open(['method'=> 'POST', 'action'=>'PredictionController@store']) !!
@foreach($matches as $match)
<tr>
<td> <small style="opacity: 0.5; font-size: 10px;">$match->date->formatLocalized('%d %B %Y') <small></td>
<td>$match->date->format('H:i')</td>
Form::hidden('match[' . $match->match_id . '][homeTeamName]', $match->homeTeam )
Form::hidden('match[' . $match->match_id . '][status]', $match->status )
<td>$match->homeTeam</td>
<td>$match->awayTeam</td>
Form::hidden('match[' . $match->match_id . '][awayTeamName]', $match->awayTeam )
<td style="width: 150px !important;"><div>Form::number('match[' . $match->match_id . '][homeTeam]' , '', [ 'class' =>'form-control-sm col col-sm-3']) <span class="ml-2" style="color: white;">-</span> Form::number('match[' . $match->match_id . '][awayTeam]' , '', ['class' =>'form-control-sm col col-sm-3 ml-2']) </div></td>
</tr>
@endforeach
Form::button('Submit', ['type' =>'submit', 'class' => 'submit-btn float-right mb-3'])
!! Form::close() !!


Any tips?










share|improve this question























  • can you add your form code also?
    – Andreas Hunter
    Nov 10 at 14:46










  • updated the code
    – Dax
    Nov 10 at 15:02














up vote
0
down vote

favorite












I have a form that has 10 inputs fields, I want to check if any of those input fields are empty. If they do are empty or have more than 2 characters I want to display only one error message. With my current code I show an error for each field that is empty. I don't want the user to see 10 error messages. I tried many other methods but doesn't seem to work.



I want the error message to say: 'Predictions can't be empty or have more than 2 characters'



The controller



 public function store(Request $request) max:2'
]);
try
collect($requestData)
->each(function ($match, $key)
Prediction::create([
'user_id' => auth()->id(),
'match_id' => $key,
'homeTeam' => $match['homeTeamName'],
'awayTeam' => $match['awayTeamName'],
'homeScore'=> $match['homeTeam'],
'awayScore'=> $match['awayTeam'],
'result' => false
]);
);
auth()->user()->participated = true;
auth()->user()->addPoint();
auth()->user()->save();

return redirect('/predictions')->with('success', 'Weekly prediction created, new predictions can be made every Tuesday!');

catch(Exception $e)
return view('error.error');





My messages.blade.php file



@if(count($errors) > 0)
@foreach($errors->all() as $error)
<div class="alert alert-red">
$error
</div>
@endforeach
@endif

@if(session('success'))
<div class="alert alert-green">
session('success')
</div>
@endif

@if(session('error'))
<div class="alert alert-danger">
session('error')
</div>
@endif


The view



@include('inc.messages')
!! Form::open(['method'=> 'POST', 'action'=>'PredictionController@store']) !!
@foreach($matches as $match)
<tr>
<td> <small style="opacity: 0.5; font-size: 10px;">$match->date->formatLocalized('%d %B %Y') <small></td>
<td>$match->date->format('H:i')</td>
Form::hidden('match[' . $match->match_id . '][homeTeamName]', $match->homeTeam )
Form::hidden('match[' . $match->match_id . '][status]', $match->status )
<td>$match->homeTeam</td>
<td>$match->awayTeam</td>
Form::hidden('match[' . $match->match_id . '][awayTeamName]', $match->awayTeam )
<td style="width: 150px !important;"><div>Form::number('match[' . $match->match_id . '][homeTeam]' , '', [ 'class' =>'form-control-sm col col-sm-3']) <span class="ml-2" style="color: white;">-</span> Form::number('match[' . $match->match_id . '][awayTeam]' , '', ['class' =>'form-control-sm col col-sm-3 ml-2']) </div></td>
</tr>
@endforeach
Form::button('Submit', ['type' =>'submit', 'class' => 'submit-btn float-right mb-3'])
!! Form::close() !!


Any tips?










share|improve this question























  • can you add your form code also?
    – Andreas Hunter
    Nov 10 at 14:46










  • updated the code
    – Dax
    Nov 10 at 15:02












up vote
0
down vote

favorite









up vote
0
down vote

favorite











I have a form that has 10 inputs fields, I want to check if any of those input fields are empty. If they do are empty or have more than 2 characters I want to display only one error message. With my current code I show an error for each field that is empty. I don't want the user to see 10 error messages. I tried many other methods but doesn't seem to work.



I want the error message to say: 'Predictions can't be empty or have more than 2 characters'



The controller



 public function store(Request $request) max:2'
]);
try
collect($requestData)
->each(function ($match, $key)
Prediction::create([
'user_id' => auth()->id(),
'match_id' => $key,
'homeTeam' => $match['homeTeamName'],
'awayTeam' => $match['awayTeamName'],
'homeScore'=> $match['homeTeam'],
'awayScore'=> $match['awayTeam'],
'result' => false
]);
);
auth()->user()->participated = true;
auth()->user()->addPoint();
auth()->user()->save();

return redirect('/predictions')->with('success', 'Weekly prediction created, new predictions can be made every Tuesday!');

catch(Exception $e)
return view('error.error');





My messages.blade.php file



@if(count($errors) > 0)
@foreach($errors->all() as $error)
<div class="alert alert-red">
$error
</div>
@endforeach
@endif

@if(session('success'))
<div class="alert alert-green">
session('success')
</div>
@endif

@if(session('error'))
<div class="alert alert-danger">
session('error')
</div>
@endif


The view



@include('inc.messages')
!! Form::open(['method'=> 'POST', 'action'=>'PredictionController@store']) !!
@foreach($matches as $match)
<tr>
<td> <small style="opacity: 0.5; font-size: 10px;">$match->date->formatLocalized('%d %B %Y') <small></td>
<td>$match->date->format('H:i')</td>
Form::hidden('match[' . $match->match_id . '][homeTeamName]', $match->homeTeam )
Form::hidden('match[' . $match->match_id . '][status]', $match->status )
<td>$match->homeTeam</td>
<td>$match->awayTeam</td>
Form::hidden('match[' . $match->match_id . '][awayTeamName]', $match->awayTeam )
<td style="width: 150px !important;"><div>Form::number('match[' . $match->match_id . '][homeTeam]' , '', [ 'class' =>'form-control-sm col col-sm-3']) <span class="ml-2" style="color: white;">-</span> Form::number('match[' . $match->match_id . '][awayTeam]' , '', ['class' =>'form-control-sm col col-sm-3 ml-2']) </div></td>
</tr>
@endforeach
Form::button('Submit', ['type' =>'submit', 'class' => 'submit-btn float-right mb-3'])
!! Form::close() !!


Any tips?










share|improve this question















I have a form that has 10 inputs fields, I want to check if any of those input fields are empty. If they do are empty or have more than 2 characters I want to display only one error message. With my current code I show an error for each field that is empty. I don't want the user to see 10 error messages. I tried many other methods but doesn't seem to work.



I want the error message to say: 'Predictions can't be empty or have more than 2 characters'



The controller



 public function store(Request $request) max:2'
]);
try
collect($requestData)
->each(function ($match, $key)
Prediction::create([
'user_id' => auth()->id(),
'match_id' => $key,
'homeTeam' => $match['homeTeamName'],
'awayTeam' => $match['awayTeamName'],
'homeScore'=> $match['homeTeam'],
'awayScore'=> $match['awayTeam'],
'result' => false
]);
);
auth()->user()->participated = true;
auth()->user()->addPoint();
auth()->user()->save();

return redirect('/predictions')->with('success', 'Weekly prediction created, new predictions can be made every Tuesday!');

catch(Exception $e)
return view('error.error');





My messages.blade.php file



@if(count($errors) > 0)
@foreach($errors->all() as $error)
<div class="alert alert-red">
$error
</div>
@endforeach
@endif

@if(session('success'))
<div class="alert alert-green">
session('success')
</div>
@endif

@if(session('error'))
<div class="alert alert-danger">
session('error')
</div>
@endif


The view



@include('inc.messages')
!! Form::open(['method'=> 'POST', 'action'=>'PredictionController@store']) !!
@foreach($matches as $match)
<tr>
<td> <small style="opacity: 0.5; font-size: 10px;">$match->date->formatLocalized('%d %B %Y') <small></td>
<td>$match->date->format('H:i')</td>
Form::hidden('match[' . $match->match_id . '][homeTeamName]', $match->homeTeam )
Form::hidden('match[' . $match->match_id . '][status]', $match->status )
<td>$match->homeTeam</td>
<td>$match->awayTeam</td>
Form::hidden('match[' . $match->match_id . '][awayTeamName]', $match->awayTeam )
<td style="width: 150px !important;"><div>Form::number('match[' . $match->match_id . '][homeTeam]' , '', [ 'class' =>'form-control-sm col col-sm-3']) <span class="ml-2" style="color: white;">-</span> Form::number('match[' . $match->match_id . '][awayTeam]' , '', ['class' =>'form-control-sm col col-sm-3 ml-2']) </div></td>
</tr>
@endforeach
Form::button('Submit', ['type' =>'submit', 'class' => 'submit-btn float-right mb-3'])
!! Form::close() !!


Any tips?







php laravel laravel-validation






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 10 at 15:01

























asked Nov 10 at 14:11









Dax

1058




1058











  • can you add your form code also?
    – Andreas Hunter
    Nov 10 at 14:46










  • updated the code
    – Dax
    Nov 10 at 15:02
















  • can you add your form code also?
    – Andreas Hunter
    Nov 10 at 14:46










  • updated the code
    – Dax
    Nov 10 at 15:02















can you add your form code also?
– Andreas Hunter
Nov 10 at 14:46




can you add your form code also?
– Andreas Hunter
Nov 10 at 14:46












updated the code
– Dax
Nov 10 at 15:02




updated the code
– Dax
Nov 10 at 15:02












3 Answers
3






active

oldest

votes

















up vote
2
down vote



accepted










I think you can do something like this:



@if($errors)
<div class="alert alert-red">
$errors->first()
</div>
@endif


If there are errors, only show the first one.






share|improve this answer



























    up vote
    0
    down vote













    You can retrieve the first error message for a given key as follows:



    foreach ($errors->first('match.*') as $message) 
    //



    For more information, check Laravel's documentation on Validation.






    share|improve this answer




















    • This is throwing errors. The foreach is invalid
      – Dax
      Nov 10 at 15:08

















    up vote
    0
    down vote













    validate() method can take a third argument specifying the cusom error message.



    To display just one, customized error message for any validation fail.



    You can do:



     $this->validate(
    $request,
    [
    'match.*.homeTeam' => 'required|max:2',
    'match.*.awayTeam' => 'required|max:2'
    ],
    ['match.*' => "Predictions can't be empty or have more than 2 characters"]);





    share|improve this answer




















      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













       

      draft saved


      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53239798%2fshowing-only-one-validation-message-for-my-array-of-inputs%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      2
      down vote



      accepted










      I think you can do something like this:



      @if($errors)
      <div class="alert alert-red">
      $errors->first()
      </div>
      @endif


      If there are errors, only show the first one.






      share|improve this answer
























        up vote
        2
        down vote



        accepted










        I think you can do something like this:



        @if($errors)
        <div class="alert alert-red">
        $errors->first()
        </div>
        @endif


        If there are errors, only show the first one.






        share|improve this answer






















          up vote
          2
          down vote



          accepted







          up vote
          2
          down vote



          accepted






          I think you can do something like this:



          @if($errors)
          <div class="alert alert-red">
          $errors->first()
          </div>
          @endif


          If there are errors, only show the first one.






          share|improve this answer












          I think you can do something like this:



          @if($errors)
          <div class="alert alert-red">
          $errors->first()
          </div>
          @endif


          If there are errors, only show the first one.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 10 at 15:00









          Camilo

          1,9061226




          1,9061226






















              up vote
              0
              down vote













              You can retrieve the first error message for a given key as follows:



              foreach ($errors->first('match.*') as $message) 
              //



              For more information, check Laravel's documentation on Validation.






              share|improve this answer




















              • This is throwing errors. The foreach is invalid
                – Dax
                Nov 10 at 15:08














              up vote
              0
              down vote













              You can retrieve the first error message for a given key as follows:



              foreach ($errors->first('match.*') as $message) 
              //



              For more information, check Laravel's documentation on Validation.






              share|improve this answer




















              • This is throwing errors. The foreach is invalid
                – Dax
                Nov 10 at 15:08












              up vote
              0
              down vote










              up vote
              0
              down vote









              You can retrieve the first error message for a given key as follows:



              foreach ($errors->first('match.*') as $message) 
              //



              For more information, check Laravel's documentation on Validation.






              share|improve this answer












              You can retrieve the first error message for a given key as follows:



              foreach ($errors->first('match.*') as $message) 
              //



              For more information, check Laravel's documentation on Validation.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Nov 10 at 14:53









              Mozammil

              1,52938




              1,52938











              • This is throwing errors. The foreach is invalid
                – Dax
                Nov 10 at 15:08
















              • This is throwing errors. The foreach is invalid
                – Dax
                Nov 10 at 15:08















              This is throwing errors. The foreach is invalid
              – Dax
              Nov 10 at 15:08




              This is throwing errors. The foreach is invalid
              – Dax
              Nov 10 at 15:08










              up vote
              0
              down vote













              validate() method can take a third argument specifying the cusom error message.



              To display just one, customized error message for any validation fail.



              You can do:



               $this->validate(
              $request,
              [
              'match.*.homeTeam' => 'required|max:2',
              'match.*.awayTeam' => 'required|max:2'
              ],
              ['match.*' => "Predictions can't be empty or have more than 2 characters"]);





              share|improve this answer
























                up vote
                0
                down vote













                validate() method can take a third argument specifying the cusom error message.



                To display just one, customized error message for any validation fail.



                You can do:



                 $this->validate(
                $request,
                [
                'match.*.homeTeam' => 'required|max:2',
                'match.*.awayTeam' => 'required|max:2'
                ],
                ['match.*' => "Predictions can't be empty or have more than 2 characters"]);





                share|improve this answer






















                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  validate() method can take a third argument specifying the cusom error message.



                  To display just one, customized error message for any validation fail.



                  You can do:



                   $this->validate(
                  $request,
                  [
                  'match.*.homeTeam' => 'required|max:2',
                  'match.*.awayTeam' => 'required|max:2'
                  ],
                  ['match.*' => "Predictions can't be empty or have more than 2 characters"]);





                  share|improve this answer












                  validate() method can take a third argument specifying the cusom error message.



                  To display just one, customized error message for any validation fail.



                  You can do:



                   $this->validate(
                  $request,
                  [
                  'match.*.homeTeam' => 'required|max:2',
                  'match.*.awayTeam' => 'required|max:2'
                  ],
                  ['match.*' => "Predictions can't be empty or have more than 2 characters"]);






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 10 at 15:18









                  Sapnesh Naik

                  4,1732938




                  4,1732938



























                       

                      draft saved


                      draft discarded















































                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53239798%2fshowing-only-one-validation-message-for-my-array-of-inputs%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      這個網誌中的熱門文章

                      Barbados

                      How to read a connectionString WITH PROVIDER in .NET Core?

                      Node.js Script on GitHub Pages or Amazon S3