【问题标题】:Multiple "required_if" on different fields within a Laravel Validator's ruleLaravel 验证器规则中不同字段上的多个“required_if”
【发布时间】:2018-11-05 04:07:38
【问题描述】:

我正在为我的帖子字段创建一些规则,但我需要在一个规则中添加来自 不同 字段的 2 个“required_if”,例如它是“AND”或“&&”但是来自不同的领域。

$validator = $this->validate([
    'form_country'          => 'required|array|min:1',
    'form_country.*'        => 'required|numeric',
    'form_tipo'             => 'required|array|min:1',
    'form_tipo.*'           => 'required|numeric|max:10', ,
    'form_fecha_iti_back'   => 'required|array|min:1',
    //so if the actual form_country is 1 AND the actual form_tipo is 3 or 5
    'form_fecha_iti_back.*' => 'required_if:form_country.*,1|required_if:form_tipo.*,3,5',
]);

(不是this question的重复)。

【问题讨论】:

  • 你使用的是什么版本的 Laravel?
  • 我使用的是 5.5 版本
  • 您需要检查验证文档 (laravel.com/docs/5.6/validation#rule-required-without-all) 并查看类似 required_with:foo,bar,... 的选项
  • 嗨 UlyssesMarx 我已经尝试过这些,但结果仍然相同
  • 只是为了确保我理解您的问题,如果 form_country 数组包含 1 并且 (非或) form_tipo 数组包含 35 然后form_fecha_iti_back 需要一个值?

标签: php laravel validation


【解决方案1】:

感谢 laracasts 的用户 https://laracasts.com/@Cronix 我设法找到了解决方案,希望它可以帮助到其他许多用户,因为它帮助了我。

//so first I create all the common rules within $rules    
$rules = [
    'form_gender' => 'required|array|min:1',
    'form_gender.*' => 'required|string|min:4|max:6',
    // others
];
//then get the requests from the needed fields
$fecha_back = request('form_fecha_iti_back');
$formCountry = request("form_country");
$form_tipo_apoyo = request("form_tipo_apoyo");

//now let's valid if we have any value and produce the custom rules according to the conditions. 
if($fecha_back){
  foreach ($fecha_back as $id => $fecha) {
       if($formCountry[$id] == 1 && $form_tipo_apoyo[$id] == 3 || $form_tipo_apoyo[$id] == 5){
          $rules["form_fecha_iti_back.".$id.""] = "required|date|after:form_fecha_iti_depart.*".$id."";
       } else{
          $rules["form_fecha_iti_back.".$id.""] = "nullable|date|after:form_fecha_iti_depart.".$id."";
       }  
  }
}
//finally we got to validate all the rules
$validator = $this->validate($rules);

【讨论】:

    猜你喜欢
    • 2019-03-21
    • 1970-01-01
    • 1970-01-01
    • 2014-04-15
    • 2020-01-24
    • 2020-05-25
    • 2017-07-08
    • 1970-01-01
    • 2017-02-06
    相关资源
    最近更新 更多