检查 Laravel 中的验证是否失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48280524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:15:15  来源:igfitidea点击:

Check if validation failed in laravel

phplaravelvalidation

提问by Atnaize

I would like to know when a validation failed by using this kind of code writing (I'm using laravel 5.4)

我想知道何时使用这种代码编写验证失败(我使用的是laravel 5.4

$this->validate($request, [
    'name' => 'required|min:2|max:255'
]);

I know that I can use this:

我知道我可以使用这个:

$validator = Validator::make($request->all(), [
    'name' => 'required|min:2|max:255'
]);

if ($validator->fails()) { //Not okay }

But I would like to keep this way of validating by using $this->validateinstead of using the Validatormodel.

但我想通过使用$this->validate而不是使用Validator模型来保持这种验证方式。

So ... is it possible to use something like:

所以......是否可以使用类似的东西:

//This is not working btw

$test = $this->validate($request, [
    'name' => 'required|min:2|max:255'
]);

if( $test )
{ //Ok }
else
{ //Not okay };

回答by lewis4u

You can use it like this:

你可以这样使用它:

$request->validate($rules);

or

或者

$request->validate([
    'name' => 'required|min:2|max:255'
]);

Then it returns the errors.

然后它返回错误。

$test = $request->validate([
           'name' => 'required|min:2|max:255'
        ]);

and you need to check if there are no errors and then you can do what ever you want.

并且您需要检查是否没有错误,然后您就可以做任何想做的事情。

In your case you need to do it like this:

在您的情况下,您需要这样做:

$validator = Validator::make($request->all(), [
    'name' => 'required|min:2|max:255'
]);

if ($validator->fails()) {
    return view('view_name');
} else {
    return view('view_name');
}