4

I have small laravel project and trying now on input validation using request. Below is my request file.

public function rules()
{
    return [
        'name' => 'required', 
        'genericname' => 'required'
    ];
}

public function messages()
{
  return  [
        'name.required' => 'Name required',
        'genericname.required' => 'Genericname required'
  ]; 
}

My blade template work as normal to show flash once errors found as below code.

@if ($errors->count() > 0)
    <div class="alert alert-warning alert-dismissible" role="alert">
        <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        {{ $errors->first() }}
    </div>
@endif

But my concern is that, Is it possible to call javascript instead if errors found. For example of my need

@if ($errors->count() > 0)
    {{ callJavaScriptAlertFunction() }}
@endif

Any advise or guidance would be greatly appreciated, Thanks.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
joenpc npcsolution
  • 737
  • 4
  • 11
  • 25
  • assuming `$errors->first()` shows an error class or element markup, alternatively, you could just invoke a javascript function when `$errors->first()`'s content is present. so you'd code that in js end – Kevin May 02 '19 at 00:50
  • Dear Jack Bashford, Could you pls get more details for ==> you could just invoke a javascript function when $errors->first()'s content is present<== Thanks – joenpc npcsolution May 02 '19 at 00:59
  • 1
    by the way, the comment above did not come from Jack Bashford :) here's an example https://stackoverflow.com/a/28059618/3859027 – Kevin May 02 '19 at 01:01

2 Answers2

5

Something like this would work:

@if ($errors->count() > 0)
    <script>
        alert("Error: " + {{ $errors->first() }});
    </script>
@endif
Syed Shoaib Abidi
  • 2,356
  • 17
  • 19
  • came to meta here please https://meta.stackoverflow.com/questions/384528/how-do-you-deal-with-an-edit-which-completely-changes-the-code-of-an-answer –  May 03 '19 at 08:24
4

You can use blade templates inside javascript. So create a function on document load.

assume you uses jQuery.

<script>
    $(document).ready(
        if({{ $errors->count() > 0 }}) {
            // your code goes here.
        }
    )
</script>
Tharaka Dilshan
  • 4,371
  • 3
  • 14
  • 28