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

时间:2015-03-29 03:39:47

标签: 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;

    });

然后我在我的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',
];

然后在位于validation.php目录的Laravel resources/lang/en文件中,如果验证返回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.

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

2 个答案:

答案 0 :(得分:11)

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

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

答案 1 :(得分:1)

这是我使用过的解决方案:

在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替换为此replaceUniqueWith函数中的$ parameters [4]

在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",
]);

这就是我的形式:)

enter image description here