我在拉拉维尔发起。我搜索了一下,没有找到如何使用一些ENUM值验证数据。在下面的代码中,我需要type
必须只是DEFAULT
或SOCIAL
。一个或另一个:
$validator = Validator::make(Input::only(['username', 'password', 'type']), [
'type' => '', // DEFAULT or SOCIAL values
'username' => 'required|min:6|max:255',
'password' => 'required|min:6|max:255'
]);
可能吗?
in:DEFAULT,SOCIAL
验证中的字段必须包含在给定的值列表中。
not_in:默认,社交<</strong> BR/>验证中的字段不得包含在给定的值列表中。
$validator = Validator::make(Input::only(['username', 'password', 'type']), [
'type' => 'in:DEFAULT,SOCIAL', // DEFAULT or SOCIAL values
'username' => 'required|min:6|max:255',
'password' => 'required|min:6|max:255'
]);
Laravel 9+
https://laravel.com/docs/10.x/validation#rule-enum
use App'Enums'ServerStatus;
use Illuminate'Validation'Rules'Enum;
$request->validate([
'status' => [new Enum(ServerStatus::class)],
]);
枚举:
namespace App'Enums;
enum ServerStatus: string {
case ACTIVE = 'active';
case INACTIVE = 'inactive';
}
所需 PHP 8.1+
接受的
答案是可以的,但我想添加如何设置in
规则以使用现有常量或值数组。
因此,如果您有:
class MyClass {
const DEFAULT = 'default';
const SOCIAL = 'social';
const WHATEVER = 'whatever';
...
您可以使用Illuminate'Validation'Rule
的 in
方法创建验证规则:
'type' => Rule::in([MyClass::DEFAULT, MyClass::SOCIAL, MyClass::WHATEVER])
或者,如果您已经将这些值分组到数组中,则可以执行以下操作:
class MyClass {
const DEFAULT = 'default';
const SOCIAL = 'social';
const WHATEVER = 'whatever';
public static $types = [self::DEFAULT, self::SOCIAL, self::WHATEVER];
然后将规则编写为:
'type' => Rule::in(MyClass::$types)
您可以使用 Rule 类,如文档所示。例如,在迁移中具有以下定义:
$table->enum('letter',['a','b','c']);
现在,您的 FormRequest 规则应包括:
class CheckInRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'letter'=>[
'required',
Rule::in(['a', 'b','c']),
],
];
}
}
其中 Rule::in (['a', 'b', 'c'])
必须包含类型为"enun"的字段的值
这对我来说在 Laravel 8.x 上工作正常
Laravel 9 php8.1
$request->validate([
'type' => [new Enum(TypeEnum::class)],
]);
小于或等于 php 8
你可以拥有枚举
class BaseEnum
{
/**
* Returns class constant values
* @return array
*/
public static function toArray(): array
{
$class = new 'ReflectionClass(static::class);
return array_values($class->getConstants());
}
/**
* @return string
*/
public function __toString(): string
{
return implode(',', static::toArray());
}
}
子枚举
class TypeEnum extends BaseEnum
{
public const DEFAULT = 'default';
public const SOCIAL = 'social';
}
在验证中,您可以通过两种不同的方式使用它
第一
$request->validate([
'type' => 'in:' . new TypeEnum(),
]);
第二
use Illuminate'Validation'Rule;
$request->validate([
'type' => Rule::in(TypeEnum::toArray())
]);
拉拉维尔
//migration
$table->enum('type',[true, false])->default(true);
//controller
$request->validate([
'type' => ['required','in:true,false']
]);