I'm creating a FormRequest that validates if it contains image depending on its field name. Below is what my rules looks like:
public function rules(){
return [
'username' => 'required|exists:users',
'key' => 'required|exists:users,activation_key',
'id' => 'sometimes|required|array|min:2',
'id.*' => 'sometimes|required|file|mimes:jpeg,jpg,png|max:5000',
'documents' => 'sometimes|required|array|min:4',
'documents.*' => 'sometimes|required|file|mimes:jpeg,jpg,png,doc,pdf,docx,zip|max:5000',
'g-recaptcha-response' => 'required',
];
}
On other terms, the array of uploaded files are validated when they are set. I'm handling this trough blade.
My request is done trough Jquery.ajax()
and using new FormData($('selector')[0])
to get the field values. I have my ajax params right so thats out of the factor.
The problem is, when making the HTTP request, with a blank form, the only thing that are being validated are username
, key
, and g-recaptcha-response
Further debugging shows that removing the sometimes
rule makes it work. But I need to only conditionally check for one(e.g /upload-id
will only show id[]
fields and /upload-documents
will only show document[]
fields).
Turns out that the problem is laravel somewhat ignores empty input[type=file]
arrays and doesn't add it into the parameter bag in the Request
Class. The workaround that i did was by using the required_if
rules on the array items validation like so:
public function rules(){
return [
'username' => 'required|exists:users',
'key' => 'required|exists:users,activation_key',
'account_type' => ['required', Rule::in(['individual', 'business'])],
'id' => 'nullable|array|min:2',
'id.*' => 'required_if:account_type,individual|file|mimes:jpeg,jpg,png|max:5000',
'documents' => 'nullable|array|min:4',
'documents.*' => 'required_if:account_type,business|file|mimes:jpeg,jpg,png,doc,pdf,docx,zip|max:5000',
'g-recaptcha-response' => 'required'
];
}
here, i have a determinant on to which between the two will be validated, so if account_type = individal
, it will only the validate deeper in the id
array