FileValidator
API reference › yii › validators › FileValidator
1 subclass
FileValidator verifies if an attribute is receiving a valid uploaded file.
Note that you should enable fileinfo PHP extension.
Properties
Section titled “Properties”| Property | Type | Description | Defined by |
|---|---|---|---|
$attributeNames read-only | array | Attribute names. | Validator |
$attributes | array| | Attributes to be validated by this validator. Default: []. | Validator |
$behaviors read-only | array<yii\<static>> | List of behaviors attached to this component. | yii\ |
$builtInValidators static | array | List of built-in validators (name => class or configuration) Default: ['boolean' => 'yii\. | Validator |
$checkExtensionByMimeType | bool | Whether to check file type (extension) with mime-type. Default: true. | FileValidator |
$clientScript | array|yii\| | Client script class to use for client-side validation. Default: null. | FileValidator |
$enableClientValidation | bool | Whether to enable client-side validation for this validator. Default: true. | Validator |
$except | array| | Scenarios that the validator should not be applied to. Default: []. | Validator |
$extensions | array| | A list of file name extensions that are allowed to be uploaded. Default: null. | FileValidator |
$isEmpty | callable| | A PHP callable that replaces the default implementation of isEmpty(). Default: null. | Validator |
$maxFiles | int | The maximum file count the given attribute can hold. Default: 1. | FileValidator |
$maxSize | int| | The maximum number of bytes required for the uploaded file. Default: null. | FileValidator |
$message | string | The error message used when a file is not uploaded correctly. Default: null. | FileValidator |
$mimeTypes | array| | A list of file MIME types that are allowed to be uploaded. Default: null. | FileValidator |
$minFiles | int | The minimum file count the given attribute can hold. Default: 0. Available since 2.0.14. | FileValidator |
$minSize | int| | The minimum number of bytes required for the uploaded file. Default: null. | FileValidator |
$on | array| | Scenarios that the validator can be applied to. Default: []. | Validator |
$sizeLimit read-only | int | The size limit for uploaded files. | FileValidator |
$skipOnEmpty | bool | Whether this validation rule should be skipped if the attribute value is null or an empty string. Default: true. | Validator |
$skipOnError | bool | Whether this validation rule should be skipped if the attribute being validated already has some validation error according to some previous rules. Default: true. | Validator |
$tooBig | string | The error message used when the uploaded file is too large. Default: null. | FileValidator |
$tooFew | string | The error message used if the count of multiple uploads less that minFiles. Default: null. Available since 2.0.14. | FileValidator |
$tooMany | string | The error message used if the count of multiple uploads exceeds limit. Default: null. | FileValidator |
$tooSmall | string | The error message used when the uploaded file is too small. Default: null. | FileValidator |
$uploadRequired | string | The error message used when no file is uploaded. Default: null. | FileValidator |
$validationAttributes read-only | array| | List of attribute names. | Validator |
$when | callable| | A PHP callable whose return value determines whether this validator should be applied. Default: null. | Validator |
$whenClient | string| | A JavaScript function name whose return value determines whether this validator should be applied on the client-side. Default: null. | Validator |
$wrongExtension | string | The error message used when the uploaded file has an extension name that is not listed in $extensions. Default: null. | FileValidator |
$wrongMimeType | string | The error message used when the file has an mime type that is not allowed by $mimeTypes property. Default: null. | FileValidator |
Methods
Section titled “Methods”| Method | Description | Defined by |
|---|---|---|
__construct() | Constructor. | yii\ |
__call() | Calls the named method which is not a class method. | yii\ |
__clone() | This method is called after the object is created by cloning an existing one. | yii\ |
__get() | Returns the value of a component property. | yii\ |
__isset() | Checks if a property is set, i.e. defined and not null. | yii\ |
__set() | Sets the value of a component property. | yii\ |
__unset() | Sets a component property to be null. | yii\ |
addError() | Adds an error about the specified attribute to the model object. | Validator |
attachBehavior() | Attaches a behavior to this component. | yii\ |
attachBehaviors() | Attaches a list of behaviors to the component. | yii\ |
behaviors() | Returns a list of behaviors that this component should behave as. | yii\ |
canGetProperty() | Returns a value indicating whether a property can be read. | yii\ |
canSetProperty() | Returns a value indicating whether a property can be set. | yii\ |
className() static | Returns the fully qualified name of this class. | yii\ |
clientValidateAttribute() | Returns the JavaScript needed for performing client-side validation. | FileValidator |
createValidator() static | Creates a validator object. | Validator |
detachBehavior() | Detaches a behavior from the component. | yii\ |
detachBehaviors() | Detaches all behaviors from the component. | yii\ |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. | yii\ |
getAttributeNames() | Returns cleaned attribute names without the ! character at the beginning. | Validator |
getBehavior() | Returns the named behavior object. | yii\ |
getBehaviors() | Returns all behaviors attached to this component. | yii\ |
getClientOptions() | Returns the client-side validation options. | FileValidator |
getFormattedClientMessage() | Returns the formatted validation message for client-side validation. | Validator |
getSizeLimit() | Returns the maximum size allowed for uploaded files. | FileValidator |
getValidationAttributes() | Returns a list of attributes this validator applies to. | Validator |
hasEventHandlers() | Returns a value indicating whether there is any handler attached to the named event. | yii\ |
hasMethod() | Returns a value indicating whether a method is defined. | yii\ |
hasProperty() | Returns a value indicating whether a property is defined for this component. | yii\ |
init() | Initializes the object. | FileValidator |
isActive() | Returns a value indicating whether the validator is active for the given scenario and attribute. | Validator |
isEmpty() | Checks if the given value is empty. | FileValidator |
off() | Detaches an existing event handler from this component. | yii\ |
on() | Attaches an event handler to an event. | yii\ |
trigger() | Triggers an event. | yii\ |
validate() | Validates a given value. | Validator |
validateAttribute() | Validates a single attribute. | FileValidator |
validateAttributes() | Validates the specified object. | Validator |
formatMessage() protected | Formats a mesage using the I18N, or simple strtr if \ is not available. | Validator |
getMimeTypeByFile() protected | Get MIME type by file path | FileValidator |
validateExtension() protected | Checks if given uploaded file have correct type (extension) according current validator settings. | FileValidator |
validateMimeType() protected | Checks the mimeType of the $file against the list in the $mimeTypes property. | FileValidator |
validateValue() protected | Validates a value. | FileValidator |
Property details
Section titled “Property details”$checkExtensionByMimeType
Section titled “$checkExtensionByMimeType ”public bool $checkExtensionByMimeType = trueWhether 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
Section titled “$extensions ”public array|string|null $extensions = nullA 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.
$maxFiles
Section titled “$maxFiles ”public int $maxFiles = 1The 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.
$maxSize
Section titled “$maxSize ”public int|null $maxSize = nullThe 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.
$mimeTypes
Section titled “$mimeTypes ”public array|string|null $mimeTypes = nullA 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.
$minFiles
Section titled “$minFiles ”public int $minFiles = 0The minimum file count the given attribute can hold.
Defaults to 0. Higher value means at least that number of files should be uploaded.
Since
2.0.14
$minSize
Section titled “$minSize ”public int|null $minSize = nullThe minimum number of bytes required for the uploaded file.
Defaults to null, meaning no limit.
$tooBig
Section titled “$tooBig ”public string $tooBig = nullThe 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()
$tooFew
Section titled “$tooFew ”public string $tooFew = nullThe 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
Since
2.0.14
$tooMany
Section titled “$tooMany ”public string $tooMany = nullThe 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
$tooSmall
Section titled “$tooSmall ”public string $tooSmall = nullThe error message used when the uploaded file is too small.
You may use the following tokens in the message:
$uploadRequired
Section titled “$uploadRequired ”public string $uploadRequired = nullThe 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.
$wrongExtension
Section titled “$wrongExtension ”public string $wrongExtension = nullThe 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.
$wrongMimeType
Section titled “$wrongMimeType ”public string $wrongMimeType = nullThe 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
Method details
Section titled “Method details”clientValidateAttribute()
Section titled “clientValidateAttribute() ”public function clientValidateAttribute(mixed $model, mixed $attribute, mixed $view): string|nullReturns 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 formname: attribute name or expression (e.g. “[0]content” for tabular input)container: the jQuery selector of the container of the input fieldinput: the jQuery selector of the input field under the context of the formerror: the jQuery selector of the error tag under the context of the containerstatus: status of the input field, 0: empty, not entered before, 1: validated, 2: pending validation, 3: validating
Parameters
| Parameter | Type | Description |
|---|---|---|
$model | mixed | The data model being validated |
$attribute | mixed | The name of the attribute to be validated. |
$view | mixed | The view object that is going to be used to render views or view files containing a model form with this validator applied. |
Returns
string|null: The client-side validation script. Null if the validator does not support client-side validation.
getClientOptions()
Section titled “getClientOptions() ”public function getClientOptions(mixed $model, mixed $attribute): arrayReturns 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.
Parameters
| Parameter | Type | Description |
|---|---|---|
$model | mixed | The model being validated |
$attribute | mixed | The attribute name being validated |
Returns
array: The client-side validation options
Since
2.0.11
getSizeLimit()
Section titled “getSizeLimit() ”public function getSizeLimit(): intReturns 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
Returns
int: The size limit for uploaded files.
init()
Section titled “init() ”public function init(): mixedInitializes the object.
This method is invoked at the end of the constructor after the object is initialized with the given configuration.
Returns
mixed
isEmpty()
Section titled “isEmpty() ”public function isEmpty(mixed $value, bool $trim = false): boolChecks 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.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | mixed | The value to be checked |
$trim | bool |
Returns
bool: Whether the value is empty
validateAttribute()
Section titled “validateAttribute() ”public function validateAttribute(mixed $model, mixed $attribute): mixedValidates a single attribute.
Child classes must implement this method to provide the actual validation logic.
Parameters
| Parameter | Type | Description |
|---|---|---|
$model | mixed | The data model to be validated |
$attribute | mixed | The name of the attribute to be validated. |
Returns
mixed
getMimeTypeByFile()
Section titled “getMimeTypeByFile() ”protected function getMimeTypeByFile(string $filePath): string|nullGet MIME type by file path
Parameters
| Parameter | Type | Description |
|---|---|---|
$filePath | string |
Returns
string|null
Throws
Since
2.0.26
validateExtension()
Section titled “validateExtension() ”protected function validateExtension(yii\web\UploadedFile $file): boolChecks if given uploaded file have correct type (extension) according current validator settings.
validateMimeType()
Section titled “validateMimeType() ”protected function validateMimeType(yii\web\UploadedFile $file): boolChecks the mimeType of the $file against the list in the $mimeTypes property.
Parameters
| Parameter | Type | Description |
|---|---|---|
$file | yii\ |
Returns
bool: Whether the $file mimeType is allowed
Throws
Since
2.0.8
See also
validateValue()
Section titled “validateValue() ”protected function validateValue(mixed $value): array|nullValidates a value.
A validator class can implement this method to support data validation out of the context of a data model.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | mixed | The data value to be validated. |
Returns
array|null: The error message and the array of parameters to be inserted into the error message. 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