habib97's avatar

Required validation on array of images is not working!

i want user to upload multiple images and if user does not select any image and submit the form then it shows required valtidation... i have done validation like this:

public function rules()
    {
        return [
           
            'space_images.*' => 'required|image|mimes:jpeg,bmp,png',
           
        ];
    }
    
    public function messages(){
        return [
            'space_images.*' => "Images must be png, jpeg or bmp",
        ];
    }

the image type validation is working but the required validation is not working please help me and thanks in advance!

0 likes
3 replies
QuentinWatt's avatar

Laravel's validator uses the period symbol (full stop) as a separator when you output messages.

As seen in documentation here. https://laravel.com/docs/5.6/validation#customizing-the-error-messages

/**
 * Get the error messages for the defined validation rules.
 *
 * @return array
 */
public function messages()
{
    return [
        'title.required' => 'A title is required',
        'body.required'  => 'A message is required',
    ];
}

If you're sending through multiple images, you'd probably want to do that as an array. So your code should probably look something like this rather.

public function rules()
    {
        return [
           
            'space_images[]' => 'required|image|mimes:jpeg,bmp,png',
           
        ];
    }
    
    public function messages(){
        return [
            'space_images[].required' => "An image is required",
            'space_images[].mimes' => "Images must be png, jpeg or bmp",
        ];
    }

And then, as many inputs as you'd like to allow for the user to upload an image. (You could even start with one, and have Javascript add another empty field each time a button is clicked.)

<input type="file" name="space_images[]"/>
<input type="file" name="space_images[]"/>
<input type="file" name="space_images[]"/>
habib97's avatar

@QuentinWatt required validation working but now mimes validation is not working and here is my view:

{!!Form::open(['action' => 'ListingsController@storeImages', 'method' => 'POST', 'enctype' => 'multipart/form-data'])!!}
        
    {{Form::file('space_images[]', ['multiple'])}}
        <br/>
        
        {{Form::submit('Submit', ['class' => 'btn btn-primary'])}}        
    {!!Form::close()!!}

Please or to participate in this conversation.