Extra validation rules for dealing with images in Laravel 5.

Overview

Image-Validator

Extra validation rules for dealing with images in Laravel 5.

NOTE: As of Laravel version 5.2, there are now built-in validation rules for image dimensions and aspect ratios. This package is not required and will no longer be maintained.

Build Status Total Downloads Latest Stable Version Latest Unstable Version Scrutinizer Code Quality SensioLabsInsight License: MIT


Installation

NOTE: Depending on your version of Laravel, you should install a different version of the package:

Laravel Version Package Version
4.* 1.x
5.0–5.3 2.1†
5.4 2.2†
5.5 not supported†

† Laravel 5.2 and later have built-in validation rules for image dimensions.

Install the package through Composer.

composer require "cviebrock/image-validator"

Add the following to your providers array in app/config/app.php:

'providers' => [
    ...
    \Cviebrock\ImageValidator\ImageValidatorServiceProvider::class,
],

Usage

Use it like any Validator rule. The package offers two rules for image validation:

image_size

$rules = [
    'my_image_field' => 'image_size:
   
    [,
    
     ]'
    
   ,
];

The values for width and _height can be integers, or integers with a modifier prefix:

  • 300 or =300 means the dimension must be exactly 300 pixels.
  • <300 means the dimension must be less than 300 pixels
  • <=300 means the dimension must be less than or equal to 300 pixels
  • >300 means the dimension must be greater than 300 pixels
  • >=300 means the dimension must be greater than or equal to 300 pixels
  • 200-300 means the dimension must be between 200 and 300 pixels (inclusive)
  • * means the dimension can be any value

If you only pass one value, it's assumed to apply to both dimensions (i.e. a square image with the given dimensions).

image_aspect

$rules = [
    'my_image_field' => 'image_aspect:
   
    '
   ,
];

The value for ratio represents width ÷ height and be either a decimal or two values (width, height; both integers):

  • 0.75
  • 3,4

The value (or first value, if providing height and width) can also be prefixed with a tilde ~ character, in which case the orientation does not matter:

  • ~3,4 means the image can have an aspect ratio of either 3:4 or 4:3.

Note that you may run into issues with floating point rounding.

Examples

// logo must be 300px wide by 400px tall
$rules = [
    'logo' => 'required|image|image_size:300,400',
];

// logo must be less than or equal to 300x300px.
$rules = [
    'logo' => 'required|image|image_size:<=300',
];

// logo must be 300px wide but can be any height
$rules = [
    'logo' => 'required|image|image_size:300,*',
];

// logo must be at least 100px tall and 200-300 pixels wide (inclusive)
$rules = [
    'logo' => 'required|image|image_size:>=100,200-300',
];

// logo must be square
$rules = [
    'logo' => 'required|image|image_aspect:1',
];

// logo must be ready for the big screen TV :)
$rules = [
    'logo' => 'required|image|image_aspect:16,9',
];

Bugs, Suggestions and Contributions

Thanks to everyone who has contributed to this project!

Please use Github for reporting bugs, and making comments or suggestions.

See CONTRIBUTING.md for how to contribute changes.

Copyright and License

image-validator was written by Colin Viebrock and is released under the MIT License.

Copyright 2013 Colin Viebrock

Thanks

Lots of thanks to https://bitbucket.org/hampel/validate-laravel for the structure of creating a package to add validator rules to Laravel, and setting up useful unit tests.

Comments
  • Laravel 5.4

    Laravel 5.4

    I can't require the image validator into Laravel 5.4.

    I get the following error:

    local.ERROR: Symfony\Component\Debug\Exception\FatalThrowableError: Type error: Argument 1 passed to Cviebrock\ImageValidator\ImageValidator::__construct() must be an instance of Symfony\Component\Translation\TranslatorInterface, instance of Illuminate\Translation\Translator given, called in /vendor/cviebrock/image-validator/src/ImageValidatorServiceProvider.php on line 35 in /vendor/cviebrock/image-validator/src/ImageValidator.php:15

    opened by RalphMRivera 7
  • Illegal string offset 'image_size' error after installation

    Illegal string offset 'image_size' error after installation

    Hey,

    Firstly, thanks for the plugin! it's much appreciated!

    I have an issue, I hope you can help me:

    My Laravel version is 4.1.24 [email protected] ~/web/mywork $ php artisan --version Laravel Framework version 4.1.24

    This is my PHP Version (using Linux Mint 16 x64): PHP 5.5.3-1ubuntu2.2 (cli) (built: Feb 28 2014 20:06:05) Copyright (c) 1997-2013 The PHP Group Zend Engine v2.5.0, Copyright (c) 1998-2013 Zend Technologies with Zend OPcache v7.0.3-dev, Copyright (c) 1999-2013, by Zend Technologies

    After installation, when I add the service provider in app/config/app.php, I get an error like this:

    Illegal string offset 'image_size'
    File: /home/arda/web/mywork/vendor/cviebrock/image-validator/src/Cviebrock/ImageValidator/ImageValidatorServiceProvider.php
    

    Error is showing this method on Whoops:

    protected function extendValidator($rule) { $method = studly_case($rule); $translation = $this->app['translator']->get('image-validator::validation'); $this->app['validator']->extend($rule, 'Cviebrock\ImageValidator\[email protected]' . $method, $translation[$rule]); $this->app['validator']->replacer($rule, 'Cviebrock\ImageValidator\[email protected]' . $method ); }

    How can I fix this?

    Edit: I've found a temporary fix, by adding a tr/validation.php (my language setting is tr) into your src folder, I've tried adding them to my app/lang/tr/validation.php but that didn't work.

    Is there a proper workaround?

    Thanks,

    opened by Ardakilic 7
  • Lumen support

    Lumen support

    Seems that there is a problem with this package in Lumen. It relies on trans() function, that is only present in Laravel, but not in Lumen (although it has a dependency on illuminate/translate)

    opened by IP-Developer 6
  • Laravel 5 throwing an error

    Laravel 5 throwing an error

    I'm guessing this package hasn't been setup for Laravel 5, but thought I'd let you know that if I try to use it I get an error:

    Exception in Store.php line 236:
    Serialization of 'Symfony\Component\HttpFoundation\File\UploadedFile' is not allowed
    

    If I don't use any image-validator rules, say just use 'photo' => 'required|image', then the validation works and I can move on to the next step.

    Anyone have any luck getting this working in L5?

    opened by alexleonard 5
  • Problem on validation message for ratio with two values.

    Problem on validation message for ratio with two values.

    If I define rule 'image_aspect:3,4' then on error, I get "The image aspect ratio must be 3". We should have "The image aspect ratio must be 3:4".

    opened by sdebacker 5
  • Support " in image_aspect">

    Support ">" in image_aspect

    /vendor/cviebrock/image-validator/src/ImageValidator.php line 118:

    // JohnLui 2015-11-12 15:33:43
    // support ">" in image_aspect
    if (substr($parameters[0],0,1)=='>') {
        if ( bccomp(substr($parameters[0], 1), $image_aspect, 10) == -1 ) {
            return true;
        }
    }
    
    opened by johnlui 4
  • Issue with laravel 5.2

    Issue with laravel 5.2

    Hello @cviebrock

    Please check with laravel version 5.2

    I got this error within form request when I try to upload.

    BadMethodCallException in Validator.php line 3255:
    Method [validateImageSize] does not exist.
    

    Thanks

    opened by sithuaung 3
  • Support custom validation message for greaterxxxx, ...

    Support custom validation message for greaterxxxx, ...

    Currently, I can't find any way that can add validation messsage for, e.g: greaterthanorequal in the locale that is not available.

    Guide me someway to do that, please.

    The result currently in chinese is like: Image 的尺寸要宽greater than or equal to 600 pixels和高greater than or equal to 600 pixels

    I find no way to change 'greaterthanorequal' => 'greater than or equal to :size pixels', this part because it has a namespace.

    opened by libern 3
  • Support for irrational numbers

    Support for irrational numbers

    I was trying an aspect ratio of 3,2, with an image of 1024x682 and another of 1024x683 but it didn't pass. I'm guessing it's because the correct height would be 862.66666666..... Can we have support for this? Maybe like flooring or ceiling the result could work. Thanks in advance!

    opened by rephiscorth 3
  • "PHP function nesting level of '5000' has been reached", if there's another extended validation

    Hey again,

    I have found a new error on my end, I hope you can help me:

    When I add another extended validation from another place, I get an error like this if image_size rule is run from validation:

    Symfony \ Component \ Debug \ Exception \ FatalErrorException
    Aborting! The New Relic imposed maximum PHP function nesting level of '5000' has been reached. This limit is to prevent the PHP execution from catastrophically running out of C-stack frames. If you think this limit is too small, adjust the value of the setting newrelic.special.max_nesting_level in the newrelic.ini file, and restart php. Please file a ticket at https://support.newrelic.com if you need further assistance.
    

    This is my extension of Laravel Validation Class: http://laravel.io/bin/MN8l

    To enable this, I've added this line in my index.php before $app->run();:

    require_once __DIR__.'/app/lib/Validation.php';

    The error occurs on the method __call() on my app/lib/validation.php as Whoops says.

    What could be the issue, is there any way to resolve this?

    Thanks in advance,

    enhancement 
    opened by Ardakilic 3
  • Argument 4 passed to Cviebrock\ImageValidator\ImageValidator::__construct() must be of the type array

    Argument 4 passed to Cviebrock\ImageValidator\ImageValidator::__construct() must be of the type array

    Hello,

    I've been getting this error since a recent update.

    Type error: Argument 4 passed to Cviebrock\ImageValidator\ImageValidator::__construct() must be of the type array, string given, called in /home/vagrant/monitoring-assistance/vendor/cviebrock/image-validator/src/ImageValidatorServiceProvider.php on line 34
    

    This error is fixed by not type hinting for an array as the forth argument. This issue from what I could debug is that the translations aren't loaded, and thus the key is sent to the constructor.

    opened by nWidart 2
Validation rules for Money and Currency

money-validation-laravel Validation rules for Money and Currency Installation composer require brokeyourbike/money-validation-laravel Usage Package us

Ivan Stasiuk 1 Oct 25, 2021
Improved abstraction for dealing with union and named types.

Check whether a reflection type or method accepts a given input

Spatie 26 Dec 26, 2022
🔒 Laravel validation rule that checks if a password has been exposed in a data breach.

?? Laravel Password Exposed Validation Rule This package provides a Laravel validation rule that checks if a password has been exposed in a data breac

Jordan Hall 85 Apr 26, 2022
高性能的验证器组件(Validation),适用于 Hyperf 或 Laravel 框架,可获得数百倍的性能提升

验证器 简介 兼容 Hyperf/Laravel Validation 规则 部分场景可获得约 500 倍性能提升 验证器可多次复用不同数据,无状态设计 规则可全局复用 智能合并验证规则 安装 环境要求 PHP >= 8.0 mbstring 扩展 ctype 扩展 安装命令 composer re

KK集团 80 Dec 9, 2022
Extension for the Laravel validation class

Intervention Validation Intervention Validation is an extension library for Laravel's own validation system. The package adds rules to validate data l

null 370 Dec 30, 2022
Laravel Validation Service

Laravel Validation Service Installation Add "prettus/laravel-repository": "1.1.*" to composer.json "prettus/laravel-validation": "1.1.*" Create a vali

Anderson Andrade 398 Nov 25, 2022
🔒 Laravel validation rule that checks if a password has been exposed in a data breach.

?? Laravel Password Exposed Validation Rule This package provides a Laravel validation rule that checks if a password has been exposed in a data breac

Jordan Hall 85 Apr 26, 2022
File uploads with validation and storage strategies

Upload This component simplifies file validation and uploading. Usage Assume a file is uploaded with this HTML form: <form method="POST" enctype="mult

Brandon Savage 1.7k Dec 27, 2022
Valitron is a simple, elegant, stand-alone validation library with NO dependencies

Valitron: Easy Validation That Doesn't Suck Valitron is a simple, minimal and elegant stand-alone validation library with NO dependencies. Valitron us

Vance Lucas 1.5k Dec 30, 2022
Lightweight and feature-rich PHP validation and filtering library. Support scene grouping, pre-filtering, array checking, custom validators, custom messages. 轻量且功能丰富的PHP验证、过滤库。支持场景分组,前置过滤,数组检查,自定义验证器,自定义消息。

PHP Validate 一个简洁小巧且功能完善的php验证、过滤库。 简单方便,支持添加自定义验证器 支持前置验证检查, 自定义如何判断非空 支持将规则按场景进行分组设置。或者部分验证 支持在进行验证前对值使用过滤器进行净化过滤内置过滤器 支持在进行验证前置处理和后置处理独立验证处理 支持自定义每

Inhere 246 Jan 5, 2023
Abstracts HTTP request input handling, providing an easy interface for data hydration and validation

Linio Input Linio Input is yet another component of the Linio Framework. It aims to abstract HTTP request input handling, allowing a seamless integrat

Linio 41 Dec 12, 2021
[READ-ONLY] Validation library from CakePHP. This repo is a split of the main code that can be found in https://github.com/cakephp/cakephp

CakePHP Validation Library The validation library in CakePHP provides features to build validators that can validate arbitrary arrays of data with eas

CakePHP 39 Oct 11, 2022
Light and extendable schema validation library

Light PHP validation library For everyone who uses MongoDB or other NoSQL solution and cares about what client sends to his/her database and looking f

Alexander Serkin 43 Sep 28, 2022
One Line Validation, For CodeIgniter 4

One Line Validation (OLV) is a package made for CodeIgniter 4 to provide a fast and single line validation experience ideal for CDN and/or API services consuming the Validation System from CodeIgniter 4.

AJ Meireles 2 Sep 21, 2021
laminas-password-validator provides a validator for character-set based input validation.

laminas-password-validator laminas-password-validator provides a validator for character-set based input validation. Installation composer require pra

null 1 Mar 8, 2022
An extensible validation library for your data with sane defaults.

Hird Hirds, also known as housecarls, was a gathering of hirdmen, who functioned as the king's personal guards during the viking age and the early mid

Asko Nõmm 13 Apr 23, 2022
FyreValidation is a free, open-source validation library for PHP.

FyreValidation FyreValidation is a free, validation library for PHP. Table Of Contents Installation Validators Rules Error Messages Installation Using

Elusive 0 Jan 15, 2022
Laravel quickly creates a verification code tool similar to Google verification code

laravel-gridCaptcha Laravel quickly creates a verification code tool similar to Google verification code laravel 快速创建一个类似于 Google 点图验证码的本地验证码扩展 介绍 lar

delete DB Flee 14 Mar 1, 2022
Custom Laravel Validator for combined unique indexes

unique_with Validator Rule For Laravel This package contains a variant of the validateUnique rule for Laravel, that allows for validation of multi-col

Felix Kiss 383 Oct 18, 2022