简体   繁体   中英

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',
        ]);

Try

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

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',
]);

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',
]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM