是否可以在自定义规则中使用现有的 Laravel 验证规则?
示例:required|string|max:100
我只想将这些规则分组到一个规则 custom_rule_name
中。
无论是这样
Validator::extend('foo', function ($attribute, $value, $parameters, $validator) {
return $value == 'required|string|max:100';//something like this
});
或
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class Uppercase implements Rule
{
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
return $value == 'required|string|max:100';//something like this
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'The :attribute must be uppercase.';
}
}
请告诉我是否有可能?
谢谢
卡里姆
最佳答案
您可以在 passes()
函数内使用 Validator
外观。像这样:
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Validator;
class Uppercase implements Rule
{
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
$validator = Validator::make([$attribute => $value], [
$attribute => 'required|string|max:100',
]);
return !$validator->fails();
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'The :attribute must be uppercase.';
}
}
关于php - 拉拉维尔 : Group existing validation rules in single custom Rule?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52778081/