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>');
        });
    }
});
1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

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.