21

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 jpg and 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 :

Custom validation error message (I’ve used 128 x 128 px) :

Set validation rules :

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 100px height.

Validate the image :

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[0] to $image_width > $parameters[0] and $image_height < $parameters[1] to $image_height > $parameters[1] and it's done.

Latest Blog

0

New Union Type in PHP – 8

A new RFC has been finished voting and accepted for PHP – 8. That is “Union Types”, which is an extension of PHP’s type system. […]