0

how can i validate an image (not in $_FILES)

this is not work

$input = array('image' => 'image.txt');
$rules = array('image' => array('Image'));

$validator = Validator::make($input, $rules);

if($validator->fails()){
    return $validator->messages();
} else {
            return true
    }

always return true

There is Laravel validate image methods

/**
 * Validate the MIME type of a file is an image MIME type.
 *
 * @param  string  $attribute
 * @param  mixed   $value
 * @return bool
 */
protected function validateImage($attribute, $value)
{
    return $this->validateMimes($attribute, $value, array('jpeg', 'png', 'gif', 'bmp'));
}

/**
 * Validate the MIME type of a file upload attribute is in a set of MIME types.
 *
 * @param  string  $attribute
 * @param  array   $value
 * @param  array   $parameters
 * @return bool
 */
protected function validateMimes($attribute, $value, $parameters)
{
    if ( ! $value instanceof File or $value->getPath() == '')
    {
        return true;
    }

    // The Symfony File class should do a decent job of guessing the extension
    // based on the true MIME type so we'll just loop through the array of
    // extensions and compare it to the guessed extension of the files.
    foreach ($parameters as $extension)
    {
        if ($value->guessExtension() == $extension)
        {
            return true;
        }
    }

    return false;
}

2 Answers 2

2

To validate a file, you have to pass the $_FILES['fileName'] array to the validator.

$input = array('image' => Input::file('image'));

and I am pretty sure that your validation rules must be lowercase.

$rules = array(
    'image' => 'image'
);

Notice that I have the removed the array from the value.

For more information, check out the validation docs

Sign up to request clarification or add additional context in comments.

Comments

0

Also make sure you open the form for files!

Make sure it has the enctype="multipart/form-data" attribute in the from tag.

1 Comment

Laravel already does it? Its validation of file with rule image already checks for mime-types

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.