I'm initiating in Laravel. I searched and not found how to validate data with some ENUM values. On below code I need that type
must be just DEFAULT
or SOCIAL
. One or other:
$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' ]);
Is possible?
in:DEFAULT,SOCIAL
The field under validation must be included in the given list of values.
not_in:DEFAULT,SOCIAL
The field under validation must not be included in the given list of values.
$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' ]);
The accepted answer is OK, but I want to add how to set the in
rule to use existing constants or array of values.
So, if you have:
class MyClass { const DEFAULT = 'default'; const SOCIAL = 'social'; const WHATEVER = 'whatever'; ...
You can make a validation rule by using Illuminate\Validation\Rule
's in
method:
'type' => Rule::in([MyClass::DEFAULT, MyClass::SOCIAL, MyClass::WHATEVER])
Or, if You have those values already grouped in an array, you can do:
class MyClass { const DEFAULT = 'default'; const SOCIAL = 'social'; const WHATEVER = 'whatever'; public static $types = [self::DEFAULT, self::SOCIAL, self::WHATEVER];
and then write the rule as:
'type' => Rule::in(MyClass::$types)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With