【问题标题】:Using custom error message with AJAX response in Laravel在 Laravel 中使用带有 AJAX 响应的自定义错误消息
【发布时间】:2021-06-08 13:10:16
【问题描述】:

如何在 json 响应中使用自定义错误消息?我正在使用 Ajax 在前端验证登录表单,并且我已经管理了如何显示验证器错误,但我不知道如何检索自定义错误消息。

这是控制器:

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()]);
        }
    
    }

这是阿贾克斯:

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

【问题讨论】:

标签: ajax laravel


【解决方案1】:

您可以通过这种方式自定义验证消息。我以您的代码为例。

$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
]);

上面的代码会覆盖 laravel 默认的消息。

【讨论】:

    猜你喜欢
    • 2017-08-12
    • 2018-11-13
    • 2015-10-02
    • 2018-08-12
    • 2016-07-10
    • 2015-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多