I’m using Laravel as the backend.
This is responsible for validating the data. It throws a json if the data is invalid.
<?php
namespace App\Http\Requests;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
class StoreArticleRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'images' => 'nullable',
'images.*' => 'image|mimes:jpg,png',
];
}
protected function failedValidation(Validator $validator)
{
throw new HttpResponseException(response()->json(['errors' => $validator->errors()], 422));
}
}
This is the error that’s being thrown when the data is invalid.
{
"errors": {
"images.0": [
"The images.0 field must be an image.",
"The images.0 field must be a file of type: jpg, png."
]
}
}
If the error happened, the user could change their mind and remove the invalid image.
As you can see here, the user doesn’t have the option to remove the image.