I’m using the Laravel Validator to test my incoming request. So to be sure that the request contains an username
and an email
, I write something like that:
$validator = Validator::make($request->all(), [ 'username' => 'required', 'email' => 'required|email' ]); if ($validator->fails()) { return response()->json('error', 400); };
But if in my request I have an additionnal params like name
, the validator will not consider it as an error and will not fail.
Have you an idea how I can make my validator more strict so that the request body match exactly?
Advertisement
Answer
Technically it’s not a validation fail in the Validator. But you could check if there are extra (unexpected) fields and send a JSON response based on that if you wanted.
Something like this maybe?
$validationRules = [ 'username' => 'required', 'email' => 'required|email' ]; $validator = Validator::make($request->all(), $validationRules); // Check if there are extra (unexpected) fields and fail in that case $extraFields = $request->except(array_keys($validationRules)); if (count($extraFields) > 0) { return response()->json('error because there are extra fields', 400); } if ($validator->fails()) { return response()->json('error', 400); } return response()->json('ok', 200);
I hope it can help you.