Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel validation for field if "image/file" is selected?

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?

like image 946
Michelle Avatar asked Jan 11 '17 10:01

Michelle


Video Answer


2 Answers

  • If the "avatar" field may not be present in the input array you want to use:

'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.


  • If the "avatar" field will absolutely be in the input array and it's value will be then 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.

like image 64
Mihailo Avatar answered Sep 27 '22 17:09

Mihailo


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',
));
like image 43
Renjith V R Avatar answered Sep 27 '22 18:09

Renjith V R