Laravel 可空验证规则不起作用

Par*_*oni 5 php laravel postman laravel-validation laravel-5.3

我最近升级到 laravel 5.4(从 5.2)以使用nullable验证规则。

我有一个act_post_code可以是integerOR 的字段null。所以我在课堂上提供了以下规则Request。

'act_post_code' => 'integer|nullable'
Run Code Online (Sandbox Code Playgroud)

在 Postman 使用 中form-data,我提供了一个 key =act_post_code及其 value = null。

我得到的答复如下:

{
    "act_post_code": [
        "The act post code must be an integer."
    ]
}
Run Code Online (Sandbox Code Playgroud)

Alm*_*itt 7

解释:

不幸的是,这似乎nullable只对某些其他验证有效。

例如:'act_post_code' => 'nullable|integer'会给你错误:"validation.integer"

不过, 'act_post_code' => 'nullable|date'效果很好。

使固定:

作为这些验证的解决方法,您可以使它们动态化。例如,在验证器之前:

$act_post_code_rules = $request->act_post_code ? 'integer' : '';

然后,在验证中:

'act_post_code' => $act_post_code_rules


小智 1

打开您的迁移文件并将此字段设置为可为空

例如

Schema::create('your_table_name', function (Blueprint $table) {
    $table->integer('act_post_code ')->nullable();    
});
Run Code Online (Sandbox Code Playgroud)

确保它存在于模型文件的可填充部分中

protected $fillable = ['act_post_code'];
Run Code Online (Sandbox Code Playgroud)