Home > Net >  Display error message in modal, after validation error in laravel
Display error message in modal, after validation error in laravel

Time:11-09

I have a problem displaying errors message in update modal form. I'm using laravel request for validation and AJAX to submit form inside a modal. I would like to see the error message for each field that are inputted incorrectly. However, I'm getting this error:

The Given data is invalid

I checked the network tab, and I'm seeing the errors there but I can't figure out why this is not showing in my fields.

Here is my script's `

function updatePassword(e, t)
    {
        e.preventDefault();

        const url    = BASE_URL   '/admin/organizations/operators/updatePassword/'   $(updatePasswordForm).find("input[name='id']").val();
        var form_data = $(t).serialize();    

        // loading('show');
        axios.post(url, form_data)
        .then(response => {
            notify(response.data.message, 'success');
            $(updatePasswordModal).modal('hide');
            // roleTable.ajax.reload()
        })
        .catch(error => {
            const response = error.response;
            if (response) {
                if (response.status === 422)
                    validationForm(updatePasswordForm, response.data.errors);
                else if(response.status === 404)
                    notify('Not found', 'error');
                else
                    notify(response.data.message, 'error');
            }
        })
        .finally(() => {
            // loading('hide');
        });
        
    }

`

Here is my Blade file `

<form id="updatePasswordForm" onsubmit="updatePassword(event, this)">
      <input type="hidden" name="id" value="">
      <div >
        <div >
          <h5  id="exampleModalLabel"> {{ __('Update Password') }}</h5>
          <button type="button"  data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div >
            <div >
              <label >{{ __('New Password') }}</label>
              <div >
                  <div >
                      <div >
                          <div >
                              <input type="password"  id="password"  name="user[password]" placeholder="{{ __('Password') }}" required>
                          </div>
                      </div>
                  </div>
                  @error('user.password')
                    <p >{{ $message }}</p>
                  @enderror
              </div>
            </div>
            <div >
              <label >{{ __('Confirm Password') }}</label>
              <div >
                  <div >
                      <div >
                          <div >
                              <input type="password"  id="confirmPassword" name="user[password_confirmation]" placeholder="{{ __('Confirm Password') }}">
                          </div>
                      </div>
                  </div>
                  @error('user.password_confirmation')
                    <p >{{ $message }}</p>
                  @enderror
              </div>
            </div>
        </div>
        <div >
          <button type="button"  data-dismiss="modal">{{ __('Close') }}</button>
          <button type="submit" >{{ __('Save') }} </button>
        </div>
      </div>
    </form>

`

Here is My Controller:

`

<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Organization\Operator\UpdatePasswordRequest;
use App\Models\OrganizationOperator;
use Illuminate\Http\Request;
use App\Services\Response;
use Exception;
use Illuminate\Support\Facades\Log;

class OrganizationController extends Controller
{
    public function updateOperatorPassword(OrganizationOperator $operator, UpdatePasswordRequest $request)
    {
        try {
            $data = $request->validated();
            $user = $data['user'];
            // dd($user['password']);
            $operator->update([
                'password' => bcrypt($user['password']),
            ]);
            return Response::success(__('Successfully updated'));
        } catch (Exception $e) {
            Log::error($e->getMessage());
            return Response::error(__('Unable to update'), [], 500);
        }
    }

}

`

Here is my Request Validation Class:

`

<?php

namespace App\Http\Requests\Admin\Organization\Operator;

use Illuminate\Foundation\Http\FormRequest;

class UpdatePasswordRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules()
    {
        return [
            'id' => ['required', 'integer', 'exists:organization_operators,id'],
            'user.password' => ['required', 'string', 'min:8', 'confirmed'],
        ];
    }
}

`

CodePudding user response:

First, I think this issue is because you send the request from the client side (which is is ajax/axios). The validation work when you submit to the server side (without ajax/axios) then response validation will display to the blade/html.

In this case, you must set error to the html manually (with innerHTML or .html() in jquery) using class/id.

for example this response from the server/api :

{ "error" : {
    "user.password" : ["invalid password"],
    ...
  }
}

in client side, you need to put that message to html tag in that case with p tag.

<p id="error-password" ></p>

$('#error-password').html(error["user.password"])
// or
$('#error-password').text(error["user.password"])

CodePudding user response:

Finally I solved this problem.

Here is my blade file:

<form id="updatePasswordForm" onsubmit="updatePassword(event, this)" >      
      <div >
        <div >
          <h5  id="exampleModalLabel"> {{ __('Update Password') }}</h5>
          <button type="button"  data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div >
            <input name="id" type="hidden"  value="">

          <div >
            <label for="">{{ __('Password') }}</label>
            <input name="password" type="password"  id="password" aria-describedby="emailHelp" placeholder="{{ __('Password') }}" required>
            <small ></small>
          </div>
          <div >
            <label for="">{{ __('Confirm Password') }}</label>
            <input name="password_confirmation" type="password"  id="password_confirmation" aria-describedby="emailHelp" placeholder="{{ __('Confirm Password') }}" required>
            <small ></small>
          </div>
        </div>
        <div >
          <button type="button"  data-dismiss="modal">{{ __('Close') }}</button>
          <button type="submit" >{{ __('Save') }} </button>
        </div>
      </div>
    </form>

Here is my Ajax:

<script type="text/javascript">
  function updatePassword(e, t)
  {
    e.preventDefault();

    const url    = BASE_URL   '/admin/organizations/operators/update-password-api/'   $(updatePasswordForm).find("input[name='id']").val();
    var form_data = $(t).serialize();  

    // loading('show');
    axios.post(url, form_data)
      .then(response => {
          notify(response.data.message, 'success');
          $(updatePasswordModal).modal('hide');
      })
      .catch(error => {
          const response = error.response;

          console.log(response.data.errors);
          if (response) {
              if (response.status === 422)
                  validationForm(updatePasswordForm, response.data.errors);
              else if(response.status === 404)
                notify('Not found', 'error');
              else
                notify(response.data.message, 'error');
          }
      })
      .finally(() => {
        // loading('hide');
      });
    
  }
</script>

Here is my PasswordRequest Validation Class:

<?php

namespace App\Http\Requests\Admin\Organization\Operator;

use Illuminate\Foundation\Http\FormRequest;

class UpdatePasswordRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules()
    {
        return [
            'id'        => ['required', 'integer', 'exists:users,id'],
            'password'  => ['required', 'string', 'min:8', 'confirmed'],
        ];
    }
}

And Here is My Controller:

public function updateOperatorPasswordApi(User $user, UpdatePasswordRequest $request)
    {
        try {
            $data = $request->validated();
            $user->update([
                'password' => bcrypt($data['password']),
            ]);
            return Response::success(__('Successfully created'));
        } catch (Exception $e) {
            Log::error($e->getMessage());
            return Response::error(__('Unable to create'), [], 500);
        }
    }
  • Related