Denis Sheremet
Denis Sheremet

Reputation: 2583

Laravel 5 input validation with name regular expression

I'm trying to do input array validation. For now I've got this:

$rules = [
    'name' => 'required|array',
];

if(array_key_exists('name', $data) && is_array($data['name'])) {
  foreach ($data['name'] as $key => $value) {
    $rules['name.' . $key] = 'required|nullable|string|max:255';
  }
}

$v = Validator::make($data, $rules);

This code works, but I want to ensure that keys is also correct. I can simply add some more checks inside foreach loop, but this makes validator itself useless as it would be simpler to check everything manually.

Perfectly, I want to achieve something like this:

$v = Validator::make($data, [
  'name' => 'required|array',
  'name.[a-z]{2}' => 'required|nullable|string|max:255'
]);

Is it possible by Validator or maybe by some extension of it?

Upvotes: 0

Views: 2003

Answers (2)

apokryfos
apokryfos

Reputation: 40663

You could do this:

In your AppServiceProvider.php extend your validator to include this rule:

Validator::extend('customrule', function ($attribute, $value, $parameters, $validator) {
      return is_array($value) && !empty(array_filter($value, function ($v) { return preg_match("/^[a-z]{2}$/",$v); });
});

Then in your code:

$rules = [ 
    'name' => 'required|array',
    'name.*' => 'required|nullable|string|max:255'
];
$extraRules = [ 
    'namekeys' => 'customrule'
];

$v = Validator::make($data, $rules);
if ($v->valid()) {
    $v2 = Validator::make(["namekeys" => array_keys($data["name"]) ], $extraRules);
}

Maybe I'm just overcomplicating things though.

Upvotes: 2

Peter Reshetin
Peter Reshetin

Reputation: 925

Sure, you may just write name.*:

$v = Validator::make($data, [
  'name' => 'required|array',
  'name.*' => 'required|nullable|string|max:255'
]);

Here are Laravel Validating Arrays Docs

Upvotes: 1

Related Questions