【问题标题】:Laravel nullable validation rule not workingLaravel 可为空的验证规则不起作用
【发布时间】:2018-07-18 09:43:40
【问题描述】:

我最近升级到 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."
    ]
}

【问题讨论】:

  • 在规则列表中的整数前使用可为空。
  • @btl 没用。同样的反应。
  • act_post_code 在您的表定义中是否可以为空?
  • 我相信是的。 act_post_code varchar(4) 默认为空,
  • 如果你尝试只使用 nullable 会发生什么

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


【解决方案1】:

打开你的迁移文件并将这个字段设置为可空

例如

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

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

protected $fillable = ['act_post_code'];

【讨论】:

    【解决方案2】:

    为了验证字段 act_post_code 可以是整数类型或可为空,您可以尝试以下操作:

    • 在迁移中声明时,有act_post_code列的表的Schema声明列如$table->integer('act_post_code')->nullable();
    • 这个可能只是用于验证'act_post_code' =>'sometimes|nullable|integer'

    【讨论】:

    【解决方案3】:

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

    然后我将它与几个测试用例一起使用:

    1. 当我输入带有非数字值的 counter 数据时,它会响应错误:
      "the counter must be a number"。
    2. 当我输入带有数值的counter 数据时,它将通过验证测试。
    3. 当我没有向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 值。

    【讨论】:

      【解决方案4】:

      说明:

      不幸的是,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

      【讨论】:

        猜你喜欢
        • 2020-03-01
        • 2018-11-09
        • 1970-01-01
        • 2017-06-21
        • 2014-11-29
        • 1970-01-01
        • 2020-07-17
        • 2023-04-02
        • 2013-12-01
        相关资源
        最近更新 更多