I have a field "image", type is file and need only to validate if image is selected, means it can be also empty.
I tried it so: 'avatar' => 'mimes:jpeg,jpg,png,gif|max:100000',
but so it is also required.
I tried still with parameters present
and sometimes
but the field is still required.
How can I validate it only if image is selected?
'avatar' => 'sometimes|mimes:jpeg,jpg,png,gif|max:100000'
In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule.
null
you want to use:'avatar' => 'nullable|mimes:jpeg,jpg,png,gif|max:100000'
The field under validation may be null. This is particularly useful when validating primitive such as strings and integers that can contain null values. To quickly accomplish this, add the nullable rule.
In your case, You have to check only if it is present or not null - Validating When there is value. So use sometimes
"In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule to your rule list"
$v = Validator::make($data, array(
'email' => 'sometimes|required|email',
));
In your case,
$v = Validator::make($data, array(
'avatar' => 'sometimes|mimes:jpeg,jpg,png,gif|max:100000',
));
Note:
The following code will do nothing because there are no rules to validate against, done because even if it's present in the POST array, you should specify rules. and the doesn't make any difference.
$v = Validator::make($data, array(
'avatar' => 'sometimes',
));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With