Laravel 3 Custom Validation Rule
Laravel provides a number of powerful validation rules including custom validation rules. All of these validation rules are really very handy and easy to use, using these rules (for image validation) you can set allowed mime types for the image, max or min image size in kilobytes etc, for example, to set rules to allow the uer to upload only
gif files you can use
'picture' => 'mimes:jpg,gif' or to make sure if the file is an image you can use
'picture' => 'image' or to st rule for an image file with maximum size of
100px you can use
'picture' => 'image|max:100' but during the development of one of my web applications I needed a rule to validate the dimension of an image to restrict the user from uploading an image less than
128px width and
128px height but there was no such a rule for this. Anyways, by the help of Laravel’s custom validation rule registration technique I have overcome this problem. The code I’ve used to validate an image’s minimum dimension
128 x 128 in my project is given below, hope it may help someone.
Register custom validation method to check minimum image dimension :
Validator::register('dimension_min', function($attribute, $value, $parameters)
$file = Input::file($attribute);
$image_info = getimagesize($file['tmp_name']);
$image_width = $image_info;
$image_height = $image_info;
if( (isset($parameters) && $parameters != 0) && $image_width < $parameters) return false;
if( (isset($parameters) && $parameters != 0) && $image_height < $parameters ) return false;
Custom validation error message (I’ve used 128 x 128 px) :
$messages = array(
'dimension_min' => 'The :attribute must be at least 128 x 128 pixels!',
Set validation rules :
$rules = array(
'imgfile' => 'mimes:png,jpg|max:500|dimension_min:128,128'
The custom validation rule
dimension_min:128,128 is being used to tell the validator that image width and height should be at least
128px, the first
128px has been used for width and the second value after comma used for minimum height and it’s possible to use different width and height, i.e.
dimension_min:128,100 for a dimension
128 x 100 width and height respectively or
dimension_min:0,100 for any width and
Validate the image :
$validation = Validator::make($input, $rules, $messages);
// Failed, redirect to back
// Validation passed, save it.
This code has been used to add a custom validation rule to restrict the minimum image dimension but it’s also possible to add a
dimension_max:128,128 to restrict the maximum image dimension by changing the code slightly, just need to change
$image_width < $parameters to
$image_width > $parameters and
$image_height < $parameters to
$image_height > $parameters and it's done.