Class yii\validators\FileValidator

Inheritanceyii\validators\FileValidator » yii\validators\Validator » yii\base\Component » yii\base\BaseObject
Implementsyii\base\Configurable
Subclassesyii\validators\ImageValidator
Available since version2.0
Source Code https://github.com/yiisoft/yii2/blob/master/framework/validators/FileValidator.php

FileValidator verifies if an attribute is receiving a valid uploaded file.

Note that you should enable fileinfo PHP extension.

Public Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
$attributeNames array Attribute names. yii\validators\Validator
$attributes array|string Attributes to be validated by this validator. yii\validators\Validator
$behaviors yii\base\Behavior[] List of behaviors attached to this component yii\base\Component
$builtInValidators array List of built-in validators (name => class or configuration) yii\validators\Validator
$checkExtensionByMimeType boolean Whether to check file type (extension) with mime-type. yii\validators\FileValidator
$enableClientValidation boolean Whether to enable client-side validation for this validator. yii\validators\Validator
$except array|string Scenarios that the validator should not be applied to. yii\validators\Validator
$extensions array|string A list of file name extensions that are allowed to be uploaded. yii\validators\FileValidator
$isEmpty callable A PHP callable that replaces the default implementation of isEmpty(). yii\validators\Validator
$maxFiles integer The maximum file count the given attribute can hold. yii\validators\FileValidator
$maxSize integer The maximum number of bytes required for the uploaded file. yii\validators\FileValidator
$message string The error message used when a file is not uploaded correctly. yii\validators\FileValidator
$mimeTypes array|string A list of file MIME types that are allowed to be uploaded. yii\validators\FileValidator
$minFiles integer The minimum file count the given attribute can hold. yii\validators\FileValidator
$minSize integer The minimum number of bytes required for the uploaded file. yii\validators\FileValidator
$on array|string Scenarios that the validator can be applied to. yii\validators\Validator
$sizeLimit integer The size limit for uploaded files. yii\validators\FileValidator
$skipOnEmpty boolean Whether this validation rule should be skipped if the attribute value is null or an empty string. yii\validators\Validator
$skipOnError boolean Whether this validation rule should be skipped if the attribute being validated already has some validation error according to some previous rules. yii\validators\Validator
$tooBig string The error message used when the uploaded file is too large. yii\validators\FileValidator
$tooFew string The error message used if the count of multiple uploads less that minFiles. yii\validators\FileValidator
$tooMany string The error message used if the count of multiple uploads exceeds limit. yii\validators\FileValidator
$tooSmall string The error message used when the uploaded file is too small. yii\validators\FileValidator
$uploadRequired string The error message used when no file is uploaded. yii\validators\FileValidator
$validationAttributes array List of attribute names. yii\validators\Validator
$when callable A PHP callable whose return value determines whether this validator should be applied. yii\validators\Validator
$whenClient string A JavaScript function name whose return value determines whether this validator should be applied on the client-side. yii\validators\Validator
$wrongExtension string The error message used when the uploaded file has an extension name that is not listed in $extensions. yii\validators\FileValidator
$wrongMimeType string The error message used when the file has an mime type that is not allowed by $mimeTypes property. yii\validators\FileValidator

Public Methods

Hide inherited methods

MethodDescriptionDefined By
__call() Calls the named method which is not a class method. yii\base\Component
__clone() This method is called after the object is created by cloning an existing one. yii\base\Component
__construct() Constructor. yii\base\BaseObject
__get() Returns the value of a component property. yii\base\Component
__isset() Checks if a property is set, i.e. defined and not null. yii\base\Component
__set() Sets the value of a component property. yii\base\Component
__unset() Sets a component property to be null. yii\base\Component
addError() Adds an error about the specified attribute to the model object. yii\validators\Validator
attachBehavior() Attaches a behavior to this component. yii\base\Component
attachBehaviors() Attaches a list of behaviors to the component. yii\base\Component
behaviors() Returns a list of behaviors that this component should behave as. yii\base\Component
canGetProperty() Returns a value indicating whether a property can be read. yii\base\Component
canSetProperty() Returns a value indicating whether a property can be set. yii\base\Component
className() Returns the fully qualified name of this class. yii\base\BaseObject
clientValidateAttribute() Returns the JavaScript needed for performing client-side validation. yii\validators\FileValidator
createValidator() Creates a validator object. yii\validators\Validator
detachBehavior() Detaches a behavior from the component. yii\base\Component
detachBehaviors() Detaches all behaviors from the component. yii\base\Component
ensureBehaviors() Makes sure that the behaviors declared in behaviors() are attached to this component. yii\base\Component
getAttributeNames() Returns cleaned attribute names without the ! character at the beginning. yii\validators\Validator
getBehavior() Returns the named behavior object. yii\base\Component
getBehaviors() Returns all behaviors attached to this component. yii\base\Component
getClientOptions() Returns the client-side validation options. yii\validators\FileValidator
getSizeLimit() Returns the maximum size allowed for uploaded files. yii\validators\FileValidator
getValidationAttributes() Returns a list of attributes this validator applies to. yii\validators\Validator
hasEventHandlers() Returns a value indicating whether there is any handler attached to the named event. yii\base\Component
hasMethod() Returns a value indicating whether a method is defined. yii\base\Component
hasProperty() Returns a value indicating whether a property is defined for this component. yii\base\Component
init() Initializes the object. yii\validators\FileValidator
isActive() Returns a value indicating whether the validator is active for the given scenario and attribute. yii\validators\Validator
isEmpty() Checks if the given value is empty. yii\validators\FileValidator
off() Detaches an existing event handler from this component. yii\base\Component
on() Attaches an event handler to an event. yii\base\Component
trigger() Triggers an event. yii\base\Component
validate() Validates a given value. yii\validators\Validator
validateAttribute() Validates a single attribute. yii\validators\FileValidator
validateAttributes() Validates the specified object. yii\validators\Validator

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
formatMessage() Formats a mesage using the I18N, or simple strtr if \Yii::$app is not available. yii\validators\Validator
validateExtension() Checks if given uploaded file have correct type (extension) according current validator settings. yii\validators\FileValidator
validateMimeType() Checks the mimeType of the $file against the list in the $mimeTypes property. yii\validators\FileValidator
validateValue() Validates a value. yii\validators\FileValidator

Property Details

$checkExtensionByMimeType public property

Whether to check file type (extension) with mime-type. If extension produced by file mime-type check differs from uploaded file extension, the file will be considered as invalid.

$extensions public property

A list of file name extensions that are allowed to be uploaded. This can be either an array or a string consisting of file extension names separated by space or comma (e.g. "gif, jpg"). Extension names are case-insensitive. Defaults to null, meaning all file name extensions are allowed.

See also $wrongExtension for the customized message for wrong file type.

public array|string $extensions null
$maxFiles public property

The maximum file count the given attribute can hold. Defaults to 1, meaning single file upload. By defining a higher number, multiple uploads become possible. Setting it to 0 means there is no limit on the number of files that can be uploaded simultaneously.

Note: The maximum number of files allowed to be uploaded simultaneously is also limited with PHP directive max_file_uploads, which defaults to 20.

See also:

public integer $maxFiles 1
$maxSize public property

The maximum number of bytes required for the uploaded file. Defaults to null, meaning no limit. Note, the size limit is also affected by upload_max_filesize and post_max_size INI setting and the 'MAX_FILE_SIZE' hidden field value. See getSizeLimit() for details.

See also:

public integer $maxSize null
$message public property

The error message used when a file is not uploaded correctly.

public string $message null
$mimeTypes public property

A list of file MIME types that are allowed to be uploaded. This can be either an array or a string consisting of file MIME types separated by space or comma (e.g. "text/plain, image/png"). The mask with the special character * can be used to match groups of mime types. For example image/* will pass all mime types, that begin with image/ (e.g. image/jpeg, image/png). Mime type names are case-insensitive. Defaults to null, meaning all MIME types are allowed.

See also $wrongMimeType for the customized message for wrong MIME type.

public array|string $mimeTypes null
$minFiles public property (available since version 2.0.14)

The minimum file count the given attribute can hold. Defaults to 0. Higher value means at least that number of files should be uploaded.

See also $tooFew for the customized message when too few files are uploaded.

public integer $minFiles 0
$minSize public property

The minimum number of bytes required for the uploaded file. Defaults to null, meaning no limit.

See also $tooSmall for the customized message for a file that is too small.

public integer $minSize null
$sizeLimit public read-only property

The size limit for uploaded files.

$tooBig public property

The error message used when the uploaded file is too large. You may use the following tokens in the message:

  • {attribute}: the attribute name
  • {file}: the uploaded file name
  • {limit}: the maximum size allowed (see getSizeLimit())
  • {formattedLimit}: the maximum size formatted with Formatter::asShortSize()
public string $tooBig null
$tooFew public property (available since version 2.0.14)

The error message used if the count of multiple uploads less that minFiles. You may use the following tokens in the message:

  • {attribute}: the attribute name
  • {limit}: the value of $minFiles
public string $tooFew null
$tooMany public property

The error message used if the count of multiple uploads exceeds limit. You may use the following tokens in the message:

  • {attribute}: the attribute name
  • {limit}: the value of $maxFiles
public string $tooMany null
$tooSmall public property

The error message used when the uploaded file is too small. You may use the following tokens in the message:

  • {attribute}: the attribute name
  • {file}: the uploaded file name
  • {limit}: the value of $minSize
  • {formattedLimit}: the value of $minSize formatted with [[\yii\i18n\Formatter::asShortSize()|Formatter::asShortSize()]
public string $tooSmall null
$uploadRequired public property

The error message used when no file is uploaded. Note that this is the text of the validation error message. To make uploading files required, you have to set $skipOnEmpty to false.

public string $uploadRequired null
$wrongExtension public property

The error message used when the uploaded file has an extension name that is not listed in $extensions. You may use the following tokens in the message:

  • {attribute}: the attribute name
  • {file}: the uploaded file name
  • {extensions}: the list of the allowed extensions.
public string $wrongExtension null
$wrongMimeType public property

The error message used when the file has an mime type that is not allowed by $mimeTypes property. You may use the following tokens in the message:

  • {attribute}: the attribute name
  • {file}: the uploaded file name
  • {mimeTypes}: the value of $mimeTypes
public string $wrongMimeType null

Method Details

clientValidateAttribute() public method

Returns the JavaScript needed for performing client-side validation.

Calls getClientOptions() to generate options array for client-side validation.

You may override this method to return the JavaScript validation code if the validator can support client-side validation.

The following JavaScript variables are predefined and can be used in the validation code:

  • attribute: an object describing the the attribute being validated.
  • value: the value being validated.
  • messages: an array used to hold the validation error messages for the attribute.
  • deferred: an array used to hold deferred objects for asynchronous validation
  • $form: a jQuery object containing the form element

The attribute object contains the following properties:

  • id: a unique ID identifying the attribute (e.g. "loginform-username") in the form
  • name: attribute name or expression (e.g. "[0]content" for tabular input)
  • container: the jQuery selector of the container of the input field
  • input: the jQuery selector of the input field under the context of the form
  • error: the jQuery selector of the error tag under the context of the container
  • status: status of the input field, 0: empty, not entered before, 1: validated, 2: pending validation, 3: validating
public string|null clientValidateAttribute ( $model, $attribute, $view )
$model yii\base\Model

The data model being validated

$attribute string

The name of the attribute to be validated.

$view yii\web\View

The view object that is going to be used to render views or view files containing a model form with this validator applied.

return string|null

The client-side validation script. Null if the validator does not support client-side validation.

getClientOptions() public method

Returns the client-side validation options.

This method is usually called from clientValidateAttribute(). You may override this method to modify options that will be passed to the client-side validation.

public array getClientOptions ( $model, $attribute )
$model yii\base\Model

The model being validated

$attribute string

The attribute name being validated

return array

The client-side validation options

getSizeLimit() public method

Returns the maximum size allowed for uploaded files.

This is determined based on four factors:

  • 'upload_max_filesize' in php.ini
  • 'post_max_size' in php.ini
  • 'MAX_FILE_SIZE' hidden field
  • $maxSize
public integer getSizeLimit ( )
return integer

The size limit for uploaded files.

init() public method

Initializes the object.

This method is invoked at the end of the constructor after the object is initialized with the given configuration.

public void init ( )
isEmpty() public method

Checks if the given value is empty.

A value is considered empty if it is null, an empty array, or an empty string. Note that this method is different from PHP empty(). It will return false when the value is 0.

public boolean isEmpty ( $value, $trim false )
$value mixed

The value to be checked

$trim boolean
return boolean

Whether the value is empty

validateAttribute() public method

Validates a single attribute.

Child classes must implement this method to provide the actual validation logic.

public void validateAttribute ( $model, $attribute )
$model yii\base\Model

The data model to be validated

$attribute string

The name of the attribute to be validated.

validateExtension() protected method

Checks if given uploaded file have correct type (extension) according current validator settings.

protected boolean validateExtension ( $file )
$file yii\web\UploadedFile
validateMimeType() protected method (available since version 2.0.8)

Checks the mimeType of the $file against the list in the $mimeTypes property.

See also $mimeTypes.

protected boolean validateMimeType ( $file )
$file yii\web\UploadedFile
return boolean

Whether the $file mimeType is allowed

throws yii\base\InvalidConfigException
validateValue() protected method

Validates a value.

A validator class can implement this method to support data validation out of the context of a data model.

protected array|null validateValue ( $value )
$value mixed

The data value to be validated.

return array|null

The error message and the array of parameters to be inserted into the error message. `php if (!$valid) {

return [$this->message, [
    'param1' => $this->param1,
    'formattedLimit' => Yii::$app->formatter->asShortSize($this->getSizeLimit()),
    'mimeTypes' => implode(', ', $this->mimeTypes),
    'param4' => 'etc...',
]];

}

return null; ` for this example message template can contain {param1}, {formattedLimit}, {mimeTypes}, {param4}

Null should be returned if the data is valid.

throws yii\base\NotSupportedException

if the validator does not supporting data validation without a model