Mohammad_Hosseini
Mohammad_Hosseini

Reputation: 2599

laravel array key validation rule

I want to validate a requested array which it's like :

  "accountType": {
    "admin" : true,
    "advertiser": true,
    "publisher": true,
    "agency": true
  },

I want to check if admin is true, do nothing and pass, but if admin is false and others are true or there is no admin in accountType object validation throw error like : invalid account type.

In Another word I want to check if there is admin in request array pass the validation, if not and there are other types shows error, also vise versa.

This is my validation but It just pass anyway:

 $validator = Validator::make($this->request->all(), [
            'accountType.admin' => 'boolean:true',
            'accountType.advertiser' => 'boolean:false',
            'accountType.publisher' => 'boolean:false',
            'accountType.agency' => 'boolean:false',
        ]);

Upvotes: 1

Views: 3073

Answers (3)

Jack Vial
Jack Vial

Reputation: 2474

You could change your values to 1 for true and 0 for false then validate like:

$validator = Validator::make($this->request->all(), [
    'accountType.admin' => 'required|min:1',
    'accountType.advertiser' => 'required|min:1',
    'accountType.publisher' => 'required|min:1',
    'accountType.agency' => 'required|min:1',
]);

Upvotes: 0

Adam
Adam

Reputation: 455

Should do the trick, from the documentation: he field under validation must be able to be cast as a boolean. Accepted input are true, false, 1, 0, "1", and "0".

$validator = Validator::make($this->request->all(), [
    'accountType.admin' => 'boolean',
    'accountType.advertiser' => 'boolean',
    'accountType.publisher' => 'boolean',
    'accountType.agency' => 'boolean',
]);

Upvotes: 0

Prashant
Prashant

Reputation: 5461

Try

$validator = Validator::make($this->request->all(), [
            'accountType.admin' => 'required|boolean:true',
            'accountType.advertiser' => 'boolean:false',
            'accountType.publisher' => 'boolean:false',
            'accountType.agency' => 'boolean:false',
        ]);

Upvotes: 1

Related Questions