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/)
たが、独自のカスタム検証ルールで機能させる方法がよくわかりません。