【问题标题】:Validating required_with and additional rules验证 required_with 和其他规则
【发布时间】:2018-09-05 14:52:20
【问题描述】:

我需要为 arrivalFromarrivalTo 两个日期字段设置验证规则。这些字段是可选的,但如果其中一个字段存在,则另一个字段是必需的,并且应该遵循特定的格式。

// Validation.
$validator = Validator::make($request->all(), [
    'amount'      => 'required|numeric',
    'arrivalFrom' => 'required_with:arrivalTo|date_format:dd/mm/yy|before:arrivalTo',
    'arrivalTo'   => 'required_with:arrivalFrom|date_format:dd/mm/yy|before:arrivalFrom',
]);

如果唯一的规则集是“required_with”,则验证有效,但一旦设置了 date_formatbeforerequired_with 就会被忽略.

Validation Message
Please not that neither of the fields "arrivalFrom" / "arrivalTo" are set.
    The arrival from does not match the format dd/mm/yy.
    The arrival from must be a date before arrival to. 
    The arrival to does not match the format dd/mm/yy.
    The arrival to must be a date before arrival to. 

有没有办法一次性完成这些验证,而不是检查输入是否存在,然后设置验证规则。

我正在使用 Laravel 5.4。

编辑:解决方案

// Validation.
$validator = Validator::make($request->all(), [
    'amount' => 'required|numeric',
    'arrivalFrom' => 'required_with:arrivalTo|nullable|date_format:d/m/y|before:arrivalTo',
    'arrivalTo' => 'required_with:arrivalFrom|nullable|date_format:d/m/y|after:arrivalFrom',
]);

【问题讨论】:

    标签: php laravel validation


    【解决方案1】:

    我自己解决了这个问题,我添加了规则 nullable,它起到了魅力的作用。因此,如果该字段不为 null,则其他验证规则将否决。

    // Validation.
    $validator = Validator::make($request->all(), [
        'amount' => 'required|numeric',
        'arrivalFrom' => 'required_with:arrivalTo|nullable|date_format:d/m/y|before:arrivalTo',
        'arrivalTo' => 'required_with:arrivalFrom|nullable|date_format:d/m/y|after:arrivalFrom',
    ]);
    

    【讨论】:

      【解决方案2】:
      // Validation.
      $validator = Validator::make($request->all(), [
          'amount'      => 'required|numeric',
          'arrivalFrom' => 'required_if:arrivalTo,"!="," "|required_with:arrivalTo|date_format:dd/mm/yy|before:arrivalTo',
          'arrivalTo'   => 'required_if:arrivalFrom,"!="," "|required_with:arrivalFrom|date_format:dd/mm/yy|before:arrivalFrom',
      ]);
      

      对此我不确定。因为我从来没有一起使用过required_ifrequired_with,但你可以试试看?不确定它是否能解决您的问题。如果可以,请告诉我。

      【讨论】:

      • 我试一试
      • 不幸的是它不起作用,但我以其他方式修复了它。
      • 没问题。请在此处分享您的代码,以便将来对某人有所帮助。 @MichaelKampmannRasmussen
      猜你喜欢
      • 2020-07-05
      • 2021-09-08
      • 1970-01-01
      • 2017-07-08
      • 2017-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多