Laravel 5.5 Conditionally adding validation rule

Viewed 1120

I have data coming in through an AJAX post like this:

data:
     0: {type: 'percent', amount: 10,…}
     1: {type: 'percent', amount: 200,…}

As you can see, the last item in the array is a problem. If the type is percent, and the amount is more than 100, the validation should fail.

I'm using the following function to validate the request:

public function validateRequest( $request ) {
    $rules = [
        'data.*.type'   => 'required|alpha',
        'data.*.amount' => 'required|min:1|int',
    ]
    $messages = [...];
    Validator::make($request->all(), $rules, $messages)->validate();
}

I've been looking on the Validation page, and I think I need to conditionally add the max:100 rule to that specific array index but only if that specific array index' type is percent. I'm just not sure how to get that done.

Thank you in advance!

1 Answers

I usually do such things as simple like this:

$rules = [
    'data.*.type'   => 'required|alpha',
    'data.*.amount' => ['required', 'min:1', 'int'],
];

foreach ($request->input('data') as $key => $value)
{
   if (array_get($value, 'type') == 'percent') {
      $rules["data.{$key}.amount"][] = 'max:100';
   }
}

Notice the array syntax for rules instead of pipe to make it easier to add additional rules.

Related