dongyi3616 2016-05-15 16:26
浏览 94

自定义表单请求的条件验证

on my controller I have:

 public function store(ProductRequest $request)

The request:

class ProductRequest extends Request
{
    public function rules()
    {
        return [
            'name' => 'required|min:3',
            'perTypeTime' => 'sometimes|required',
            'per_type_id' => 'required'
        ];
    }
}

I want to change the perTypeTime rule above to be conditional depending on if per_type_id field == 1.

If I initiated the validator in the controller I believe I could do something like the below:

$v = Validator::make($data, [
    'per_type_id' => 'required|email'
]);

$v->sometimes('perTypeTime', 'required|max:500', function($input)
{
    return $input->per_type_id == 1;
});

Is there a way to do this, while keeping my custom request. I like how this approach keeps the controller cleaner.

I can't seem to access the validator on the request object. Is there a way to specify this condition inside the request itself, or to access the validator from the request object, or is there another way?

  • 写回答

3条回答 默认 最新

  • duancha1065 2016-05-15 16:36
    关注

    You can do that

    I want to change the perTypeTime rule above to be conditional depending on if per_type_id field == 1.

    within your rules() method in your ProductRequest. For details see required_if:anotherfield,value in the Laravel documentation validation rules.

    public function rules()
    {
        return [
            'name'          => 'required|min:3',
            'perTypeTime'   => 'required_if:per_type_id,1',
            'per_type_id'   => 'required'
        ];
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)