douzhantao2857 2016-08-21 02:14
浏览 43
已采纳

Laravel 5.2条件验证

I initially had fields first_name, last_name, password, email as the fields in my sign up form. I need to add an option for signing up as a business.

My initial validation rules:

protected function validator(array $data)
{
    return Validator::make($data, [
        'first_name' => 'required|max:255',
        'last_name' => 'required|max:255',
        'email' => 'required|email|max:255|unique:users',
        'password' => 'required|min:6|confirmed',
    ]);
}

I need to add a business_name field. I need the validation to be:

first_name and last_name are required xor business_name is required.

How can I do this in Laravel 5.2? I was looking at the sometimes rule - but I'm not sure if that is how this should be done.

edit:

I suppose it could almost be accomplished via:

protected function validator(array $data)
{
    return Validator::make($data, [
        'first_name' => 'sometimes|max:255',
        'last_name' => 'sometimes|max:255',
        'business_name'=>'sometimes|max:255',
        'email' => 'required|email|max:255|unique:users',
        'password' => 'required|min:6|confirmed',
    ]);
}

Although from my understanding of the sometimes rule, it will only validate if the key is present in the input array, therefore first_name could be present, and last_name could be non-existent which would would still validate as a "pass". This isn't the behavior that I'd like.

  • 写回答

1条回答 默认 最新

  • doutan2111 2016-08-21 02:26
    关注

    What you might be looking for is the required_without:foo,bar,...

    That validation rule says 'The field under validation must be present and not empty only when any of the other specified fields are not present'.

    So you might have business_name => required_without:first_name,last_name

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致