【问题标题】:Validation closure not firing?验证关闭不触发?
【发布时间】:2021-07-11 16:55:12
【问题描述】:

我想在 Laravel 5.6 中使用闭包创建自定义验证,如文档中所述: https://laravel.com/docs/5.6/validation#using-closures

这是我的代码:

   public function store(Request $request)
    {
        \Illuminate\Support\Facades\Validator::make($request->all(), [
            'trainer' => [
                function ($attribute, $value, $fail) {
                    return $fail($attribute . ' is invalid.');
                },
            ],
        ]);

        if ($validator->fails()) {
          dd($validator->messages());
        }

        dd('NO ERROR??');
   }

测试它使用

$this->post('/my_test_route', []);

返回

没有错误??

这是为什么?如果我将代码更改为

   public function store(Request $request)
   {
        Illuminate\Support\Facades\Validator::make($request->all(), [
            'trainer' => 'required',
        ]);

        dd('NO ERROR??');
   }

我得到了预期:

Illuminate\Support\MessageBag^ {#2408
  #messages: array:1 [
    "trainer" => array:1 [
      0 => "The trainer field is required."
    ]
  ]
  #format: ":message"
}

我错过了什么?

【问题讨论】:

    标签: laravel validation laravel-5


    【解决方案1】:

    发现问题。因为没有给出 trainer 作为输入,所以没有执行自定义验证方法!

    添加trainer 作为参数起作用:

    $this->post('/my_test_route', ['trainer' => 'test']);
    

    或作为替代用途:

    'trainer' => [
                   'required',
                    function ($attribute, $value, $fail) {
                        return $fail($attribute . ' is invalid.');
                    },
                ],
    

    或者,如果你想在没有提供参数的情况下执行验证方法,并且你不想让它成为必需,那么你的自定义规则应该实现Illuminate\Contracts\Validation\ImplicitRule(参见https://laravel.com/docs/8.x/validation#implicit-rules

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-11
      • 2011-08-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-07
      相关资源
      最近更新 更多