Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom validation is not taking AllowEmpty option

I have input type file for uploading image. It’s not required field. So I set allowEmpty option as true. But my model is not taking this option. Validation code :

public $validate = array(
    'image' => array(
        'isImage' => array(
            'rule' => 'isImage',
            'message' => 'Please upload images only',
            'allowEmpty' => true,
            //'required' => true,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
    ),
);

public function isImage($field = null) {
    $file_info = $field['image_path'];
    $image_types = array("image/jpeg", "image/gif", "image/jpg", "image/png");

    $result  = false;
    if (in_array($file_info['type'], $image_types)) {
        $result = true;
    }
    return $result;
}

Or any other rule for validating image type.

like image 268
Kushal Avatar asked Jun 01 '26 08:06

Kushal


1 Answers

In your example, allowEmpty won't even matter - it uses the custom method isImage() and returns false. End validation / fail.

If you're going to use a custom validation rule, just use it. Try something like this within the function:

if(empty($field)) return true;
like image 98
Dave Avatar answered Jun 04 '26 13:06

Dave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!