Laravel 数组验证

4
$rules = [
            'user_id'           => 'required|exists:users,id',
            'preparat_id'       => 'required|exists:preparats,id',
            'zoom'              => 'required|numeric',
            'comment'           => '',
            'type'              => 'in:' . Annotation::ANN_RECTANGLE . ',' . Annotation::ANN_CIRCLE . ',' . Annotation::ANN_POLYGON . ',' . Annotation::ANN_PIN,
            'point_x'           => 'array|required|numeric',
            'point_y'           => 'array|required|numeric',
        ];

        $this->validate($request, $rules);

point_xpoint_y是输入的数组。

我的规则是:

point_xpoint_y必须存在。

我如何发送数据:

  • point_x[0] = 123;
  • point_y[0] = 123;

正确


  • point_x[0] = 123;
  • point_y[0] = 123;
  • point_x[1] = 123;
  • point_y[1] = 123;
  • point_x[2] = 123;
  • point_y[2] = 123;

正确


point_x[0] = 123; point_y[0] = "SO";

错误


point_y[0] = 123;

错误


  • point_x[0] = 123;
  • point_y[0] = 123;
  • point_x[1] = 123;
  • point_y[1] = "Taadaa";
  • point_x[2] = 123;
  • point_y[2] = 123;

错误

我的Laravel版本是5.4。

如何编写一个检查上述内容的规则。我尝试了数组参数,但它不起作用。


我在这里解决了一个类似的问题:https://stackoverflow.com/questions/44715505/how-to-validate-multiple-value-with-single-field-in-laravel-validation/44715782#44715782 - aaron0207
2个回答

2

尝试仅对数组point_xpoint_y遵循以下规则:

$this->validate($request, [
    'point_x' => 'required',
    'point_y' => 'required',
    'point_x.*' => 'numeric',
    'point_y.*' => 'numeric',
], 
     $messages = [

     ]
);

请查看文档:数组输入验证

0
  public function rules($array)
    {
      $rules = [  
            'user_id'           => 'required|exists:users,id',
            'preparat_id'       => 'required|exists:preparats,id',
            'zoom'              => 'required|numeric',
            'comment'           => '',
            'type'              => 'in:' . Annotation::ANN_RECTANGLE . ',' . Annotation::ANN_CIRCLE . ',' . Annotation::ANN_POLYGON . ',' . Annotation::ANN_PIN,];

      foreach($array as $key => $val)
      {
        $rules[$key] = 'required|numeric';
      }
      return $rules;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接