Laravel动态生成的字段验证



我有一个提交大量图像的表单,假设有5张图像。我把它们命名为img1,img2,img5。现在我正在逐一验证这些字段。

my validation code

$rules = [
'image1' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:3072',
'image2' => 'image|mimes:jpeg,png,jpg,gif,svg|max:3072',
'image3' => 'image|mimes:jpeg,png,jpg,gif,svg|max:3072',
'image4' => 'image|mimes:jpeg,png,jpg,gif,svg|max:3072',
'image5' => 'image|mimes:jpeg,png,jpg,gif,svg|max:3072',
];
$msg = [
'image1.required' => 'Image is required',
'image1.image' => 'Please upload an Image for Image ',
'image1.mimes' => 'Image type should be jpeg or jpg or png or gif or svg',
'image1.max' => 'Image size should be less than or equal 3MB',
'image2.image' => 'Please upload an Image for Image ',
'image2.mimes' => 'Image type should be jpeg or jpg or png or gif or svg',
'image2.max' => 'Image size should be less than or equal 3MB',
'image3.image' => 'Please upload an Image for Image ',
'image3.mimes' => 'Image type should be jpeg or jpg or png or gif or svg',
'image3.max' => 'Image size should be less than or equal 3MB',
'image4.image' => 'Please upload an Image for Image ',
'image4.mimes' => 'Image type should be jpeg or jpg or png or gif or svg',
'image4.max' => 'Image size should be less than or equal 3MB',
'image5.image' => 'Please upload an Image for Image ',
'image5.mimes' => 'Image type should be jpeg or jpg or png or gif or svg',
'image5.max' => 'Image size should be less than or equal 3MB',
];
$this->validate($req, $rules, $msg);

你能告诉我是否有更好的方法吗?:)

使用Array代替文件名

多个文件的Laravel验证规则。

$rule = ['image.*' => 'required|mimes:jpeg,png,jpg,gif,svg|max:3072'];
$msg = ['image.*.image' => 'Please upload an Image for Image ',
'image.*.mimes' => 'Image type should be jpeg or jpg or png or gif or svg',
'image.*.max' => 'Image size should be less than or equal 3MB'];

您可以将它们全部提交到数组$images

并使验证:-

$rules = [
"images"   =>"required|array|min:1",
"images.*" =>"required|image|mimes:jpeg,png,jpg,gif,svg|max:3072"
]

也不需要设置每次验证的消息,除非你想改变laravel的默认验证消息

相关内容

  • 没有找到相关文章

最新更新