0

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 class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel"> {{ __('Update Password') }}</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
            <div class="form-group row">
              <label class="col-sm-4 col-form-label required">{{ __('New Password') }}</label>
              <div class="col-sm-8">
                  <div class="row">
                      <div class="col-sm-12">
                          <div class="form-group @error('user.password') error @enderror">
                              <input type="password" class="form-control" id="password"  name="user[password]" placeholder="{{ __('Password') }}" required>
                          </div>
                      </div>
                  </div>
                  @error('user.password')
                    <p class="error-message">{{ $message }}</p>
                  @enderror
              </div>
            </div>
            <div class="form-group row">
              <label class="col-sm-4 col-form-label required">{{ __('Confirm Password') }}</label>
              <div class="col-sm-8">
                  <div class="row">
                      <div class="col-sm-12">
                          <div class="form-group @error('user.password_confirmation') error @enderror">
                              <input type="password" class="form-control" id="confirmPassword" name="user[password_confirmation]" placeholder="{{ __('Confirm Password') }}">
                          </div>
                      </div>
                  </div>
                  @error('user.password_confirmation')
                    <p class="error-message">{{ $message }}</p>
                  @enderror
              </div>
            </div>
        </div>
        <div class="modal-footer justify-content-center">
          <button type="button" class="btn btn-secondary mr-3" data-dismiss="modal">{{ __('Close') }}</button>
          <button type="submit" class="btn btn-primary">{{ __('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'],
        ];
    }
}

3
  • Firstly, name="user[password]" and @error('user.password') .. @enderror should be same string value in both name attribute and error directive but you have used different. Next, error directive only works when you submit the form and get redirect back with errors values, but you do it from AJAX to send request and get response. So, you have do it manually using JavaScript to show error message to the form field. Commented Nov 8, 2022 at 6:44
  • attribute in rules() and in form should match. And where is rule for confirmpassword? I would recommend jquery validate geeksforgeeks.org/form-validation-using-jquery Commented Nov 8, 2022 at 7:56
  • Here is my confirmed password validation rules in request class public function rules() { return [ 'password' => ['required', 'string', 'min:8', 'confirmed'], ]; } Commented Nov 9, 2022 at 8:36

2 Answers 2

0

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"])
Sign up to request clarification or add additional context in comments.

Comments

0

Finally I solved this problem.

1. I change my controller

public function updateOperatorPassword(OrganizationOperator $operator, UpdatePasswordRequest $request) 

TO

public function updateOperatorPasswordApi(User $user, UpdatePasswordRequest $request) 

AND

try {
    $data = $request->validated();
    $user = $data['user'];
    // dd($user['password']);
    $operator->update([
        'password' => bcrypt($user['password']),
    ]);
    return Response::success(__('Successfully updated'));
}

TO

try {
    $data = $request->validated();
    $user->update([
        'password' => bcrypt($data['password']),
    ]);
    return Response::success(__('Successfully created'));
}

2. I change my blade file

<div class="row">
    <div class="col-sm-12">
        <div class="form-group @error('user.password_confirmation') error @enderror">
            <input type="password" class="form-control" id="confirmPassword" name="user[password_confirmation]" placeholder="{{ __('Confirm Password') }}">
        </div>
    </div>
</div>
@error('user.password_confirmation')
    <p class="error-message">{{ $message }}</p>
@enderror

TO

<div class="form-group">
    <label for="">{{ __('Password') }}</label>
    <input name="password" type="password" class="form-control" id="password" aria-describedby="emailHelp" placeholder="{{ __('Password') }}" required>
    <small class="form-text error-message"></small>
</div>

AND

<div class="row">
    <div class="col-sm-12">
        <div class="form-group @error('user.password_confirmation') error @enderror">
            <input type="password" class="form-control" id="confirmPassword" name="user[password_confirmation]" placeholder="{{ __('Confirm Password') }}">
        </div>
    </div>
</div>
@error('user.password_confirmation')
    <p class="error-message">{{ $message }}</p>
@enderror

TO

<div class="form-group">
    <label for="">{{ __('Confirm Password') }}</label>
    <input name="password_confirmation" type="password" class="form-control" id="password_confirmation" aria-describedby="emailHelp" placeholder="{{ __('Confirm Password') }}" required>
    <small class="form-text error-message"></small>
</div>

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand what has changed in your codes that has solved your problem. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.