请教一下,laravel使用ajax提交数据时validate验证返回422响应这个有什么好的处理方法吗?

假如_丶

不贴源码就是脑筋急转弯…

GOD_Nt 回复 假如_丶
public function store(Request $request)
    {
        $this->validate($request, [
            'new_house_id' => 'required|integer',
            'is_thinking' => 'required|max:32',
            'around_score' => 'required|in:0,1,2,3,4,5',
            'traffic_score' => 'required|in:0,1,2,3,4,5',
            'green_score' => 'required|in:0,1,2,3,4,5',
            'desc' => 'required|min:6|max:255'
        ], [], [
            'new_house_id' => '新房',
            'is_thinking' => '是否考虑',
            'around_score' => '周边配套',
            'traffic_score' => '交通方便',
            'green_score' => '绿化环境',
            'desc' => '点评'
        ]);
        $comment = $this->commentRepository->store($request->all());
        return response()->json(['msg' => '添加评论成功,审核成功后才会显示哦~']);
    }

这个是ajax请求的控制器方法,在validate验证不通过是,返回422响应

假如_丶 回复 GOD_Nt

http 422状态 请求格式正确,但是由于含有语义错误,无法响应。(RFC 4918 WebDAV)423 Locked   当前资源被锁定。(RFC 4918 WebDAV)

你截取下看看吧…

Terry Lucas

public function store(Request $request)
{
this>validate(this->validate(request, [
‘new_house_id’ => ‘required|integer’,
‘is_thinking’ => ‘required|numeric|max:32’,
‘around_score’ => ‘required|numeric|in:0,1,2,3,4,5’,
‘traffic_score’ => ‘required|numeric|in:0,1,2,3,4,5’,
‘green_score’ => ‘required|numeric|in:0,1,2,3,4,5’,
‘desc’ => ‘required|numeric|min:6|max:255’
], [], [
‘new_house_id’ => ‘新房’,
‘is_thinking’ => ‘是否考虑’,
‘around_score’ => ‘周边配套’,
‘traffic_score’ => ‘交通方便’,
‘green_score’ => ‘绿化环境’,
‘desc’ => ‘点评’
]);
$comment = this>commentRepository>store(this->commentRepository->store(request->all());
return response()->json([‘msg’ => ‘添加评论成功,审核成功后才会显示哦~’]);
}

Terry Lucas

以上的答案 不知道是否可以帮到你 laravel validator 如果使用了max in min between 等时 laravel自动会去验证是否时数字 如果你之前不进行numeric规则设定 会直接验证不过的

GOD_Nt 回复 Terry Lucas

你这是说了啥?

huigezizj

同求,我是在request层进行的验证,直接就是422错误和 {args.data.text: [“tag最多50个字符!”]}
在前台怎么处理

yff
$.ajax({
     success: function(){

     },
     error: function(data){
           console.log(data);
     }
})
GOD_Nt 回复 yff

对啊,现在只能写在error里面,但是F12有个报错总是感觉很别扭