Laravel 5中自定义验证规则的自定义占位符

no.*_*no. 6 php laravel laravel-5 laravel-validation

我在Laravel应用程序中创建了一组自定义验证规则.我首先创建了一个目录validators.php中的App\Http文件:

/**
 * 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;

    });
Run Code Online (Sandbox Code Playgroud)

我然后在我的AppServiceProvider.php文件中添加这个(同时也添加use Illuminate\Validation\Factory;在这个文件的顶部):

public function boot(Factory $validator) {

    require_once app_path('Http/validators.php');

}
Run Code Online (Sandbox Code Playgroud)

然后在我的表单请求文件中,我可以调用自定义验证规则,如下所示:

$rules = [
    'image' => 'required|image|image_width:50,800',
];
Run Code Online (Sandbox Code Playgroud)

然后在validation.php位于resources/lang/en目录中的Laravel 文件中,我将向数组添加另一个键/值,以便在验证返回false并失败时显示错误消息,如下所示:

'image_width' => 'The :attribute width must be between :min and :max pixels.',
Run Code Online (Sandbox Code Playgroud)

一切正常,它正确检查图像,如果失败则显示错误消息,但我不知道如何替换: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.

replace*在主Validator.php文件中看到了一些函数(vendor/laravel/framework/src/Illumiate/Validation/),但我似乎无法弄清楚如何使用我自己的自定义验证规则.

Mar*_*łek 11

我没有用这种方式,但你可以使用:

$validator->replacer('image_width_max',
    function ($message, $attribute, $rule, $parameters) {
        return str_replace([':min', ':max'], [$parameters[0], $parameters[1]], $message);
    });
Run Code Online (Sandbox Code Playgroud)