【发布时间】:2015-06-02 05:44:06
【问题描述】:
我在我的 Laravel 应用程序中创建了一组自定义验证规则。我首先在App\Http 目录中创建了一个validators.php 文件:
/**
* Require a certain number of parameters to be present.
*
* @param int $count
* @param array $parameters
* @param string $rule
* @return void
* @throws \InvalidArgumentException
*/
function requireParameterCount($count, $parameters, $rule) {
if (count($parameters) < $count):
throw new InvalidArgumentException("Validation rule $rule requires at least $count parameters.");
endif;
}
/**
* Validate the width of an image is less than the maximum value.
*
* @param string $attribute
* @param mixed $value
* @param array $parameters
* @return bool
*/
$validator->extend('image_width_max', function ($attribute, $value, $parameters) {
requireParameterCount(1, $parameters, 'image_width_max');
list($width, $height) = getimagesize($value);
if ($width >= $parameters[0]):
return false;
endif;
return true;
});
然后我将在我的AppServiceProvider.php 文件中添加包含此内容(同时还在此文件顶部添加use Illuminate\Validation\Factory;):
public function boot(Factory $validator) {
require_once app_path('Http/validators.php');
}
然后在我的表单请求文件中,我可以调用自定义验证规则,如下所示:
$rules = [
'image' => 'required|image|image_width:50,800',
];
然后在位于 resources/lang/en 目录下的 Laravel validation.php 文件中,我向数组中添加另一个键/值,以在验证返回 false 且失败时显示错误消息,如下所示:
'image_width' => 'The :attribute width must be between :min and :max pixels.',
一切正常,它会正确检查图像,如果失败则显示错误消息,但我不确定如何将:min 和:max 替换为表单请求文件中声明的值(50,800),同样的方式:attribute 被替换为表单字段名称。所以目前它显示:
The image width must be between :min and :max pixels.
而我希望它像这样显示
The image width must be between 50 and 800 pixels.
我在 Validator.php 主文件 (vendor/laravel/framework/src/Illumiate/Validation/) 中看到了一些 replace* 函数,但我似乎不太明白如何让它与我自己的自定义验证规则一起工作。
【问题讨论】:
标签: php laravel laravel-5 laravel-validation