6

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',
];

次に、ディレクトリにある Laravelvalidation.phpファイルで、resources/lang/en別のキー/値を配列に追加して、検証が false を返し、失敗した場合にエラー メッセージを表示します。次のようにします。

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

すべて正常に動作し、画像を正しくチェックし、失敗した場合はエラー メッセージを表示しますが、フォーム リクエスト ファイル (50,800) で宣言された値に置き換える方法がわかりません。同じ方法:minでフォーム フィールドに置き換えられます。名前。したがって、現在は次のように表示されます。:max: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/)たが、独自のカスタム検証ルールで機能させる方法がよくわかりません。

4

3 に答える 3

11

私はこのように使用したことはありませんが、おそらく次のように使用できます。

$validator->replacer('image_width_max',
    function ($message, $attribute, $rule, $parameters) {
        return str_replace([':min', ':max'], [$parameters[0], $parameters[1]], $message);
    });
于 2015-03-29T07:50:04.007 に答える
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",
]);

これは私のフォームでは次のようになります:)

ここに画像の説明を入力

于 2015-08-09T12:11:53.313 に答える