skip to Main Content

I’m building an API that takes in an array of ‘additional_data’ but I want some control over the fields that can be passed in.

Take the following JSON:

{
    "name": "Joe Bloggs",
    "additional_data": {
        "type": "example",
        "other_type": "example"
    }
}

My current validation attempt:

return [
    'name' => ['required'],
    'additional_data.*' => ['sometimes', Rule::in(['type'])]
];

This always fails validation, what I’m looking for is to validate the key of the array so I can make sure the keys passed in are part of a ‘whitelist’.

3

Answers


  1. What you do now is you try to validate content of additional_data.type and additional_data.other_type.

    You can do this by adding a custom validator. For example

    Validator::extend('check_additional_data_keys', function($attribute, $value, $parameters, $validator) {
        return is_array($value) && array_diff(array_keys($value), ['type', 'other_type']) === 0);
    });
    

    and use it inside your current rules

    return [
        'name' => ['required'],
        'additional_data' => ['check_additional_data_keys'],
        'additional_data.*' => ['required', 'string'],
    ];
    
    Login or Signup to reply.
  2. Just specify your whitelist keys using the array validation rule:

    return [
        'name' => 'required',
        'additional_data' => [
            'sometimes', 
            'array:type',
        ],
    ];
    
    Login or Signup to reply.
  3. 1- In case you want applay same validation on all arrays’ keys you can use the following:

       return [
            'name' => 'required',
            'additional_data' => ['array', Rule::in(['type'])]
            ];
    

    2- In case each key in the array needs different validation use the following:

       return [
            'name' => 'required',
            'additional_data' => 'array',
            'additional_data.ky1' => ['your validation here'],
            'additional_data.ky2' => ['your validation here'],
            ];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search