jonnybarnes's avatar

How do I make my validation error message more specific

I have a form where one of the inputs is named “photo”. I’m also using HTML5’s “multiple” option on the input to allow several photos to be uploaded at once. This means the resulting $request->input('photo') is an array of UploadedFIles and the builtin validator for file size was failing.

So I’ve written my own rule by extending the validator in my AppServiceProvider like so:

Validator::extend('photosize', function ($attribute, $value, $parameters, $validator) {
    foreach ($value as $file) {
        if ($file->getSize() > 5000000) {
            return false;
        }
    }

    return true;
});

Then in the controller I can use the rule and add an error message like so:

$validator = Validator::make(
    $request->all(),
    ['photo' => 'photosize'],
    ['photosize' => 'Uploaded file exceeds size limit 5MB']
);

However this means regardless which file was too big the error message is the same. Is it possible to have that information in the error message?

0 likes
1 reply
chaibialaa's avatar

Well this depends on your errors handling .. You can add other validations for other staff and catch any unhandled error with that. You can use a foreach validation instead of all, that way, you can show a message per each image validation :)

Please or to participate in this conversation.