Skip to content
PHP Ecosystem
Explore

FileValidator

API reference › yii › validators › FileValidator

classyii\validators\FileValidator
ExtendsValidator » yii\base\Component » yii\base\BaseObject
Implementsyii\base\Configurable
Since2.0
Sourceframework/validators/FileValidator.php
1 subclass

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

Note that you should enable fileinfo PHP extension.

PropertyTypeDescriptionDefined by
$attributeNames read-onlyarrayAttribute names.Validator
$attributesarray|stringAttributes to be validated by this validator. Default: [].Validator
$behaviors read-onlyarray<yii\base\Behavior<static>>List of behaviors attached to this component.yii\base\Component
$builtInValidators staticarrayList of built-in validators (name => class or configuration) Default: ['boolean' => 'yii\validators\BooleanValidator', 'captcha' => 'yii\captcha\CaptchaValidator', 'compare' => 'yii\validators\CompareValidator', 'date' => 'yii\validators\DateValidator', 'datetime' => ['class' => 'yii\validators\DateValidator', 'type' => \yii\validators\DateValidator::TYPE_DATETIME], 'time' => ['class' => 'yii\validators\DateValidator', 'type' => \yii\validators\DateValidator::TYPE_TIME], 'default' => 'yii\validators\DefaultValueValidator', 'double' => 'yii\validators\NumberValidator', 'each' => 'yii\validators\EachValidator', 'email' => 'yii\validators\EmailValidator', 'exist' => 'yii\validators\ExistValidator', 'file' => 'yii\validators\FileValidator', 'filter' => 'yii\validators\FilterValidator', 'image' => 'yii\validators\ImageValidator', 'in' => 'yii\validators\RangeValidator', 'integer' => ['class' => 'yii\validators\NumberValidator', 'integerOnly' => true], 'match' => 'yii\validators\RegularExpressionValidator', 'number' => 'yii\validators\NumberValidator', 'required' => 'yii\validators\RequiredValidator', 'safe' => 'yii\validators\SafeValidator', 'string' => 'yii\validators\StringValidator', 'trim' => ['class' => 'yii\validators\TrimValidator', 'skipOnArray' => true], 'unique' => 'yii\validators\UniqueValidator', 'url' => 'yii\validators\UrlValidator', 'ip' => 'yii\validators\IpValidator'].Validator
$checkExtensionByMimeTypeboolWhether to check file type (extension) with mime-type. Default: true.FileValidator
$clientScriptarray|yii\validators\client\ClientValidatorScriptInterface|nullClient script class to use for client-side validation. Default: null.FileValidator
$enableClientValidationboolWhether to enable client-side validation for this validator. Default: true.Validator
$exceptarray|stringScenarios that the validator should not be applied to. Default: [].Validator
$extensionsarray|string|nullA list of file name extensions that are allowed to be uploaded. Default: null.FileValidator
$isEmptycallable|nullA PHP callable that replaces the default implementation of isEmpty(). Default: null.Validator
$maxFilesintThe maximum file count the given attribute can hold. Default: 1.FileValidator
$maxSizeint|nullThe maximum number of bytes required for the uploaded file. Default: null.FileValidator
$messagestringThe error message used when a file is not uploaded correctly. Default: null.FileValidator
$mimeTypesarray|string|nullA list of file MIME types that are allowed to be uploaded. Default: null.FileValidator
$minFilesintThe minimum file count the given attribute can hold. Default: 0. Available since 2.0.14.FileValidator
$minSizeint|nullThe minimum number of bytes required for the uploaded file. Default: null.FileValidator
$onarray|stringScenarios that the validator can be applied to. Default: [].Validator
$sizeLimit read-onlyintThe size limit for uploaded files.FileValidator
$skipOnEmptyboolWhether this validation rule should be skipped if the attribute value is null or an empty string. Default: true.Validator
$skipOnErrorboolWhether this validation rule should be skipped if the attribute being validated already has some validation error according to some previous rules. Default: true.Validator
$tooBigstringThe error message used when the uploaded file is too large. Default: null.FileValidator
$tooFewstringThe error message used if the count of multiple uploads less that minFiles. Default: null. Available since 2.0.14.FileValidator
$tooManystringThe error message used if the count of multiple uploads exceeds limit. Default: null.FileValidator
$tooSmallstringThe error message used when the uploaded file is too small. Default: null.FileValidator
$uploadRequiredstringThe error message used when no file is uploaded. Default: null.FileValidator
$validationAttributes read-onlyarray|nullList of attribute names.Validator
$whencallable|nullA PHP callable whose return value determines whether this validator should be applied. Default: null.Validator
$whenClientstring|nullA JavaScript function name whose return value determines whether this validator should be applied on the client-side. Default: null.Validator
$wrongExtensionstringThe error message used when the uploaded file has an extension name that is not listed in $extensions. Default: null.FileValidator
$wrongMimeTypestringThe error message used when the file has an mime type that is not allowed by $mimeTypes property. Default: null.FileValidator
MethodDescriptionDefined by
__construct()Constructor.yii\base\BaseObject
__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
__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.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() staticReturns the fully qualified name of this class.yii\base\BaseObject
clientValidateAttribute()Returns the JavaScript needed for performing client-side validation.FileValidator
createValidator() staticCreates a validator object.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.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.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\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.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\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.Validator
validateAttribute()Validates a single attribute.FileValidator
validateAttributes()Validates the specified object.Validator
formatMessage() protectedFormats a mesage using the I18N, or simple strtr if \Yii::$app is not available.Validator
getMimeTypeByFile() protectedGet MIME type by file pathFileValidator
validateExtension() protectedChecks if given uploaded file have correct type (extension) according current validator settings.FileValidator
validateMimeType() protectedChecks the mimeType of the $file against the list in the $mimeTypes property.FileValidator
validateValue() protectedValidates a value.FileValidator
public bool $checkExtensionByMimeType = true

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.

public array|string|null $extensions = null

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.

public int $maxFiles = 1

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.

public int|null $maxSize = null

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.

public array|string|null $mimeTypes = null

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.

public int $minFiles = 0

The 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

public int|null $minSize = null

The minimum number of bytes required for the uploaded file.

Defaults to null, meaning no limit.

public string $tooBig = null

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 $tooFew = null

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

Since

2.0.14

public string $tooMany = null

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 $tooSmall = null

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 $uploadRequired = null

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 $wrongExtension = null

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 $wrongMimeType = null

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 function clientValidateAttribute(mixed $model, mixed $attribute, mixed $view): string|null

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

Parameters

ParameterTypeDescription
$modelmixedThe data model being validated
$attributemixedThe name of the attribute to be validated.
$viewmixedThe 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.

public function getClientOptions(mixed $model, mixed $attribute): array

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.

Parameters

ParameterTypeDescription
$modelmixedThe model being validated
$attributemixedThe attribute name being validated

Returns

array: The client-side validation options

Since

2.0.11

public function getSizeLimit(): int

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

Returns

int: The size limit for uploaded files.

public function init(): mixed

Initializes the object.

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

Returns

mixed

public function isEmpty(mixed $value, bool $trim = false): bool

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.

Parameters

ParameterTypeDescription
$valuemixedThe value to be checked
$trimbool

Returns

bool: Whether the value is empty

public function validateAttribute(mixed $model, mixed $attribute): mixed

Validates a single attribute.

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

Parameters

ParameterTypeDescription
$modelmixedThe data model to be validated
$attributemixedThe name of the attribute to be validated.

Returns

mixed

protected function getMimeTypeByFile(string $filePath): string|null

Get MIME type by file path

Parameters

ParameterTypeDescription
$filePathstring

Returns

string|null

Throws

Since

2.0.26

protected function validateExtension(yii\web\UploadedFile $file): bool

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

Parameters

ParameterTypeDescription
$fileyii\web\UploadedFile

Returns

bool

protected function validateMimeType(yii\web\UploadedFile $file): bool

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

Parameters

ParameterTypeDescription
$fileyii\web\UploadedFile

Returns

bool: Whether the $file mimeType is allowed

Throws

Since

2.0.8

See also

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

Validates a value.

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

Parameters

ParameterTypeDescription
$valuemixedThe 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