Bug*_*ayi 4 php validation laravel laravel-validation
Laravel 5.5
public function register(Request $request){
request()->validate([
'email' => 'required:email'
'password' => 'required|min:6'
]);
return response()->json(["message" => "Hello World"]);
}
Run Code Online (Sandbox Code Playgroud)
如果验证器失败,则不提供错误消息.重定向主页面
Ser*_*nko 11
如果您使用的代码在验证失败时将您重定向到上一页,则表示您没有告诉服务器您希望接收哪种响应.
设置正确的标头以获取JSON.它将使验证器发送JSON作为响应.例如:
$.ajax({
headers: {
Accept : "application/json"
},
...
});
Run Code Online (Sandbox Code Playgroud)
然后这段代码将按预期工作:
public function register(Request $request)
{
$request->validate([
'email' => 'required:email'
'password' => 'required|min:6'
]);
return response()->json(["message" => "Hello World"]);
}
Run Code Online (Sandbox Code Playgroud)
在 Postman 应用程序中测试我的其余 api 时,我遇到了同样的问题。
为了修改控制器类文件中的代码,我这样做并获得了 json 响应,而不是重定向到主页。
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6',
]);
if ($validator->fails()) {
return response()->json($validator->errors());
} else {
// do something
}
}
Run Code Online (Sandbox Code Playgroud)
在它看起来像下面的代码之前,它被重定向到主页
这是验证器功能
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6',
]);
}
public function register(Request $request)
{
// Here the request is validated. The validator method is located
// inside the RegisterController, and makes sure the name, email
// password and password_confirmation fields are required.
$this->validator($request->all())->validate();
// A Registered event is created and will trigger any relevant
// observers, such as sending a confirmation email or any
// code that needs to be run as soon as the user is created.
event(new Registered($user = $this->create($request->all())));
// After the user is created, he's logged in.
$this->guard()->login($user);
// And finally this is the hook that we want. If there is no
// registered() method or it returns null, redirect him to
// some other URL. In our case, we just need to implement
// that method to return the correct response.
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3130 次 |
| 最近记录: |