我最近升级到Laravel 5.4(从5.2(使用nullable
验证规则。
我有一个字段act_post_code
,可以是integer
或null
。因此,我在Request
类中提供了以下规则。
'act_post_code' => 'integer|nullable'
在使用form-data
的Postman中,我提供了一个键= act_post_code
,其值= null
。
我得到的响应如下:
{
"act_post_code": [
"The act post code must be an integer."
]
}
说明:
不幸的是,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
为了验证可以是类型的字段act_post_code
,您可以尝试以下内容:
- 在迁移中声明时,表的表格
act_post_code
列出了列,如$table->integer('act_post_code')->nullable();
- 这个可能只是为您验证
'act_post_code' =>'sometimes|nullable|integer'
一个人可以死亡并转储请求参数,并检查实际值是null还是" null"(在字符串中(。有时,当通过JavaScript提交表单时,我们会使用FormData((将数据附加到表单上,在这些情况下,它可能会像字符串类型中一样发送null值。
array:5 [
"firstName" => "Kaustubh"
"middleName" => "null" // null as string
"lastName" => "Bagwe"
"contactNumber" => null // null value
"photo" => null
"_method" => "PUT"
]
打开迁移文件,并将此字段作为无效
用于例如
Schema::create('your_table_name', function (Blueprint $table) {
$table->integer('act_post_code ')->nullable();
});
确保它存在于"填充部分"中的模型文件中
protected $fillable = ['act_post_code'];
在一项测试之后,我发现无效的规则仅在我们传递的数据实际上是一个空数据时起作用。
因此,在我的测试案例中,我使用这样的验证规则:
"counter" => "nullable|numeric"
在刀片文件中,我使用 Form::text('counter','')
作为输入数据。
然后我在几个测试用例中使用它:
- 当我输入具有非数值的
counter
数据时,它将响应错误:
"the counter must be a number"
。 - 当我输入具有数字值的
counter
数据时,它将通过验证测试。 - 当我不将任何数据输入
counter
时,它将通过验证测试。
因此,我使用dd($request_data)
手动检查数据,或者如果您使用AJAX仅return $request_data
并使用console.log("data")
打印它,则喜欢:
$.ajax({
type:'POST',
data:{_token:"{{ csrf_token() }}",
counter:$('input[name="counter"]').val()
},success:function(data){
console.log(data);
}
});
发现,当输入字段清空时,它将给出null
值。