Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel IN Validation or Validation by ENUM Values

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?

like image 230
Maykonn Avatar asked Mar 11 '15 00:03

Maykonn


2 Answers

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' ]); 
like image 58
Alupotha Avatar answered Sep 18 '22 08:09

Alupotha


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) 
like image 31
Aleksandar Avatar answered Sep 20 '22 08:09

Aleksandar