1

How can I use custom error messages in a json response? I'm using Ajax to validate a login form in frontend and I've already manage how to display the Validator errors, but I can't figure out how I can retrieve a custom error message.

This is the controller:

public function LoginValid(Request $request){

    $validator = Validator::make($request->all(), [
        'email' => ['required', 'string', 'email' ],
        'password' => ['required', 'string', 'max:255'],
    ]);

    if($validator->passes()){

    $user = User::where('email', $request->email)->first();

    if ($user &&
        Hash::check($request->password, $user->password)) {

$credentials = $request->only('email', 'password');

    if (Auth::attempt($credentials)) {
        
        return redirect()->intended('dashboard');

    }else{

    return response()->json('should be any custom message here');

      }  
    }

    }else{
            return response()->json(['error'=>$validator->errors()->all()]);
        }
    
    }

And here's the Ajax:

 $(document).ready(function() {
    $("#btn-login").click(function(e) {
        e.preventDefault();

        var _token = $("input[name='_token']").val();
        var email = $("input[name='email']").val();
        var password = $("input[name='password']").val();

        $.ajax({
            url: "{{ route('login-valid') }}",
            type: 'POST',
            data: { _token: _token, email: email, password:password },
            success: function(data) {

                if ($.isEmptyObject(data.error)) {

                    window.location.href = 'dashboard';

                } else {
                    printErrorMsg(data.error);
                }
            }
        });
    });

    function printErrorMsg(msg) {
        $(".print-error-msg").find("ul").html('');
        $(".print-error-msg").css('display', 'block');
        $.each(msg, function(key, value) {
            $(".print-error-msg").find("ul").append('<li>' + value + '</li>');
        });
    }
});
Nayana
  • 127
  • 1
  • 13
  • Does this answer your question? [How to return custom error message from controller method validation](https://stackoverflow.com/questions/40067212/how-to-return-custom-error-message-from-controller-method-validation) – miken32 Mar 10 '21 at 17:14

1 Answers1

0

you can customize validation messages in this way. I am using your code for an example.

$validator = Validator::make($request->all(), [
        'email' => ['required', 'string', 'email' ],
        'password' => ['required', 'string', 'max:255'],
    ], [
'email.required' => 'email is required',
'email.string' => 'email should be valid',
'email.email' => 'email should be in proper format'
 .
 .
 .
 .
and so on
]);

above code will overwrite the laravel default messages.

Jayant
  • 280
  • 2
  • 6