Laravel array validation
$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_x
and point_y
- array input.
My rule:
point_x
and point_y
must exist.
How I am sending data:
- point_x [0] = 123;
- point_y [0] = 123;
TRUE
- point_x [0] = 123;
- point_y [0] = 123;
- point_x [1] = 123;
- point_y [1] = 123;
- point_x [2] = 123;
- point_y [2] = 123;
TRUE
point_x [0] = 123; point_y [0] = "SO";
WRONG
point_y [0] = 123;
WRONG
- point_x [0] = 123;
- point_y [0] = 123;
- point_x [1] = 123;
- point_y [1] = "Taadaa";
- point_x [2] = 123;
- point_y [2] = 123;
WRONG
My Laravel version is 5.4
How to write a rule for validation as above. I tried using an array parameter but it doesn't work.
+3
source to share
2 answers
Try the following rules for arrays point_x
and point_y
,
$this->validate($request, [
'point_x' => 'required',
'point_y' => 'required',
'point_x.*' => 'numeric',
'point_y.*' => 'numeric',
],
$messages = [
]
);
See docs Checking Array Input
+2
source to share
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;
}
0
source to share