Validating aaax form for Laravel with input field

In the Laravel 5.1 project

I get Ajax Response As Error

{ "success":false, "errors":{ "drugs_power":["The drugs power field is required."] } } 

I need a validation of such a picture enter image description here I can do this with the laravel validator with this code (return From Controller),

 $this->validate($request, [ 'drugs_name' => 'required|unique:drugs', 'drugs_group_name' => 'required', 'drugs_power' => 'required' ]); 

Show In blade.php with this code

 <div class="form-group{{ $errors->has('drugs_power') ? ' has-error' : '' }}"> <label for="userName">Power</label> <div> <input type="text" class="form-control" name="drugs_power" value="{{old('drugs_power')}}"> @if ($errors->has('drugs_power')) <span class="help-block"> <strong>{{ $errors->first('drugs_power') }}</strong> </span> @endif </div> </div> 

How can I do ajax + laravel check this way?

+5
source share
3 answers

Passing the third parameter to validate allows you to specify a custom message, as shown here . You can use “dot” notation to indicate an error message in a specific field.

 $this->validate($request, [ 'drugs_name' => 'required|unique:drugs', 'drugs_group_name' => 'required', 'drugs_power' => 'required' ], [ 'drugs_power.required' => 'Your custom message here.' ]); 
+1
source

Assuming u is using the Laravel request object correctly, you will get 422 response code in your browser.

If you want to catch this globally, you can extend the default ajax behavior by adding the following code to your JS.

 $(function () { $.ajaxSetup({ statusCode: { 422: function (data) { $.each(data.responseJSON, function (k, v) { // do something with the error }) } } }); }); 
0
source

Are you looking for https://github.com/whipsterCZ/laravel-ajax

He does exactly what you want and more !

submitting and Validating forms using ajax is as simple as this - no configuration required

HTML

 <form action="" class="ajax">...</form> 

controller

 public function update(ClientRequest $request, Client $client) { $client->update($request->all()); $request->session()->flash('success', 'Client has been updated.'); return \Ajax::redirect(route('clients.index')); } 

It validates the form (through a custom FormRequest) and shows errors (in the errorBag or directly above the input)

0
source

Source: https://habr.com/ru/post/1245875/


All Articles