4

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

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! This seems to do exactly as I wanted :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.