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

Custom placeholders for custom validation rules in Laravel 5

我在 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 文件中,我将另一个 key/value 添加到数组以显示错误消息,如果验证returns false 失败,像这样:

'image_width' => 'The :attribute width must be between :min and :max pixels.',

一切正常,它会正确检查图像,如果失败则显示错误消息,但我不确定如何将 :min:max 替换为表单中声明的​​值request file(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* 函数,但我似乎不太明白如何让它与我自己的一起工作自定义验证规则。

我没有这样使用过,但你可能会使用:

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

这是我使用的解决方案:

在composer.json中:

"autoload": {
    "classmap": [
        "app/Validators"
    ],

在App/Providers/AppServiceProvider.php:

public function boot()
{
    $this->app->validator->resolver(
        function ($translator, $data, $rules, $messages) {
            return new CustomValidator($translator, $data, $rules, $messages);
        });
}

在App/Validators/CustomValidator.php

namespace App\Validators;

use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Validator as Validator;

class CustomValidator extends Validator
{
    // This is my custom validator to check unique with
    public function validateUniqueWith($attribute, $value, $parameters)
    {
        $this->requireParameterCount(4, $parameters, 'unique_with');
        $parameters    = array_map('trim', $parameters);
        $parameters[1] = strtolower($parameters[1] == '' ? $attribute : $parameters[1]);
        list($table, $column, $withColumn, $withValue) = $parameters;

        return DB::table($table)->where($column, '=', $value)->where($withColumn, '=', $withValue)->count() == 0;
    }

    // All you have to do is create this function changing
    // 'validate' to 'replace' in the function name
    protected function replaceUniqueWith($message, $attribute, $rule, $parameters)
    {
        return str_replace([':name'], $parameters[4], $message);
    }
}

:name is replace by $parameters[4] in this replaceUniqueWith function

在App/resources/lang/en/validation.php

<?php
return [
    'unique_with' => 'The :attribute has already been taken in the :name.',
];

在我的控制器中,我这样调用这个验证器:

$organizationId = session('organization')['id'];    
$this->validate($request, [
    'product_short_title' => "uniqueWith:products,short_title,
                              organization_id,$organizationId,
                              Organization",
]);

这是我的表单中的样子:)

我在 Laravel 5.4 中使用类似的东西:

AppServiceProvider.php

public function boot()
{
    \Validator::extend('contains_field', 'App\Validators\ContainsFieldValidator@validate');
    \Validator::replacer('contains_field', 'App\Validators\ContainsFieldValidator@replace');
}

App\Validators\ContainsFieldValidator.php

class ContainsFieldValidator
{
    public function validate($attribute, $value, $parameters, Validator $validator)
    {
        $required = $parameters[0];
        $requiredDefault = isset($parameters[1]) ?: null;

        if (!$required && !$requiredDefault) {
            return false;
        }

        $requiredValue = isset($validator->attributes()[$required]) ? $validator->attributes()[$required] : $requiredDefault;

        return !(strpos($value, $requiredValue) === false);
    }

    public function replace($message, $attribute, $rule, $parameters)
    {
        return str_replace([':required'], str_replace('_', ' ', $parameters[0]), $message);
    }
}