Laravel可空验证规则不起作用

时间:2018-02-07 23:26:33

标签: php laravel laravel-5.3 postman laravel-validation

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

我有一个字段act_post_code,可以是integernull。所以我在Request课程中提供了以下规则。

'act_post_code' => 'integer|nullable'

在使用form-data的邮递员中,我提供了一个键= act_post_code,其值为null

我得到的回应如下:

{
    "act_post_code": [
        "The act post code must be an integer."
    ]
}

4 个答案:

答案 0 :(得分:1)

说明:

不幸的是,看来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 :(得分:0)

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

例如

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

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

protected $fillable = ['act_post_code'];

答案 2 :(得分:0)

为了验证可以是整数或可空类型的字段CASE WHEN refresh_date IS NULL THEN NULL ELSE refresh_date END AS RefreshDate ,您可以尝试以下内容:

  • 在迁移中声明时,列act_post_code的表的架构声明了act_post_code
  • 这个可能适合您验证$table->integer('act_post_code')->nullable();

答案 3 :(得分:0)

经过一些测试,我发现只有当我们传递的数据确实是空数据时,可空规则才有效。
所以在我的测试用例中,我使用像这样的验证规则:
"counter" => "nullable|numeric"
在刀片文件中,我使用Form::text('counter','')作为输入数据的元素。

然后我将其用于少数测试用例:

  1. 当我输入具有非数字值的counter数据时,它将出现以下错误:
    "the counter must be a number"
  2. 当我输入带有数字值的counter数据时,它将通过验证测试。
  3. 当我没有向counter输入任何数据时,它将通过验证测试。

所以我使用dd($request_data)手动检查数据,或者如果仅使用return $request_data使用ajax并使用console.log("data")打印数据,例如:

$.ajax({
type:'POST',
data:{_token:"{{ csrf_token() }}",
    counter:$('input[name="counter"]').val()
},success:function(data){
  console.log(data);   
 }
});

,发现当输入字段为空时,它将给出null的值。

相关问题