作为Laravel开发人员,我们经常需要验证上传的图像,以确保它们满足一定的尺寸要求。开箱即用,Laravel的验证规则只适用于数值,不适用于base64编码的图像。max
在这篇文章中,我们将逐步扩展 Laravel 的验证以处理自定义 base64 图像大小验证。通过编写自定义验证规则,我们可以在应用中需要上传图像的任何位置重复使用此逻辑。
自定义验证规则
所有自定义验证规则都是通过扩展 in 方法注册的。首先,我们将使用 Laravel 的方法定义逻辑:
ValidatorbootAppServiceProviderValidator::extend
Validator::extend('base64_image_size', function ($attribute, $value, $parameters, $validator) {
// Decode the image
$decodedImage = base64_decode($value);
// Get image size in kilobytes
$imageSize = strlen($decodedImage) / 1024;
// Check if image is below max size
return $imageSize <= $parameters[0];
});
在这里,我们正在解码 base64 编码的图像,以获得其二进制大小(以字节为单位)。然后我们转换为千字节以与参数中定义的最大大小进行比较。如果图像低于最大大小,则验证通过。
自定义错误消息
接下来,我们将使用以下方法自定义错误消息:Validator::replacer
Validator::replacer('base64_image_size', function ($message, $attribute, $rule, $parameters) {
return str_replace([':attribute', ':max'], [$attribute, $parameters[0]], $message);
});
这将替换为字段名称和定义的最大大小。消息本身在语言文件中定义:
:attribute:maxresources/lang/xx/validation.php
'base64_image_size' => 'The :attribute must not be larger than :max KB.',
用法
最后,我们可以在验证期间使用此自定义规则:
$validator = Validator::make($request->all(), [
'image' => 'required|base64_image_size:500',
]);
if ($validator->fails()) {
// Image too large
}
通过扩展 Laravel 的验证功能,我们构建了一种可重用的方式来验证整个应用程序中的 base64 图像大小。相同的方法可用于任何不适合内置规则的验证逻辑。