Note that you should enable fileinfo PHP extension.
Since: 2.0
Author: Qiang Xue (qiang.xue@gmail.com)
Inheritance: extends Validator
 /**
  * @inheritdoc
  */
 public function init()
 {
     parent::init();
     if ($this->uploadRequired === null) {
         $this->uploadRequired = Yii::t('yii', 'Please select a correct url.');
     }
 }
 private function upload_file($fileAttribute = self::XLS_FILE, array $extensions = null, $maxSize = 10485760)
 {
     $this->_uploaded_file = (new UploadedFile())->getInstance($this->owner, $fileAttribute);
     if ($this->_uploaded_file) {
         $fileValidator = new FileValidator(['extensions' => is_array($extensions) ? $extensions : ['xls', 'xlsx'], 'maxSize' => $maxSize]);
         if ($fileValidator->validate($this->_uploaded_file, $error)) {
             return true;
         } else {
             $this->owner->addError($fileAttribute, $error);
         }
     } else {
         if (isset($_FILES['Dvk'])) {
             $this->owner->addError($fileAttribute, Yii::t('app', 'Choose file for import!'));
         }
     }
     return false;
 }
 /**
  * @inheritdoc
  */
 protected function validateValue($file)
 {
     $res = parent::validateValue($file);
     if (empty($res)) {
         return $this->_validateImage($file);
     }
     return $res;
 }
 /**
  * @inhertidoc
  */
 public function run()
 {
     Yii::$app->getResponse()->format = Response::FORMAT_JSON;
     $file = UploadedFile::getInstanceByName($this->fileInputName);
     $validationOptions = ArrayHelper::merge(['extensions' => 'gif, jpg, png', 'maxSize' => 2 * 1024 * 1024], $this->fileValidation);
     $validator = new FileValidator($validationOptions);
     if (!$validator->validate($file, $errmsg)) {
         return ['errcode' => 1, 'errmsg' => $errmsg];
     }
     if (null === $this->fileName) {
         $this->fileName = md5($file->name . time());
     }
     $file_path = $this->targetDirectory . DIRECTORY_SEPARATOR . $this->fileName;
     if ($file->saveAs($file_path)) {
         return ['errcode' => 0, 'errmsg' => 'Uploaded successfully!', 'file' => ['name' => $file->name, 'newFileName' => $this->fileName, 'alias' => $this->baseUrl . '/' . $this->fileName, 'uploaded' => Yii::getAlias($this->baseUrl) . '/' . $this->fileName . '?_' . $_SERVER['REQUEST_TIME']]];
     }
     return ['errcode' => 1, 'errmsg' => 'Error occured'];
 }
 /**
  * @throws Exception
  */
 protected function validate()
 {
     if (empty($this->validateOptions)) {
         return;
     }
     $file = $this->uploadfile;
     $error = [];
     $validator = new FileValidator($this->validateOptions);
     if (!$validator->validate($file, $error)) {
         throw new Exception($error);
     }
 }
 /**
  * @inheritdoc
  */
 protected function getClientOptions($model, $attribute)
 {
     $options = parent::getClientOptions($model, $attribute);
     $label = $model->getAttributeLabel($attribute);
     if ($this->notImage !== null) {
         $options['notImage'] = Yii::$app->getI18n()->format($this->notImage, ['attribute' => $label], Yii::$app->language);
     }
     if ($this->minWidth !== null) {
         $options['minWidth'] = $this->minWidth;
         $options['underWidth'] = Yii::$app->getI18n()->format($this->underWidth, ['attribute' => $label, 'limit' => $this->minWidth], Yii::$app->language);
     }
     if ($this->maxWidth !== null) {
         $options['maxWidth'] = $this->maxWidth;
         $options['overWidth'] = Yii::$app->getI18n()->format($this->overWidth, ['attribute' => $label, 'limit' => $this->maxWidth], Yii::$app->language);
     }
     if ($this->minHeight !== null) {
         $options['minHeight'] = $this->minHeight;
         $options['underHeight'] = Yii::$app->getI18n()->format($this->underHeight, ['attribute' => $label, 'limit' => $this->minHeight], Yii::$app->language);
     }
     if ($this->maxHeight !== null) {
         $options['maxHeight'] = $this->maxHeight;
         $options['overHeight'] = Yii::$app->getI18n()->format($this->overHeight, ['attribute' => $label, 'limit' => $this->maxHeight], Yii::$app->language);
     }
     return $options;
 }
 public function testValidateAttributeErrNoTmpDir()
 {
     $m = $this->createModelForAttributeTest();
     $val = new FileValidator();
     $val->validateAttribute($m, 'attr_err_tmp');
     $this->assertTrue($m->hasErrors('attr_err_tmp'));
     $this->assertSame(Yii::t('yii', 'File upload failed.'), current($m->getErrors('attr_err_tmp')));
 }
 /**
  * @param $attribute
  * @return array|null|object|Validator
  */
 private function getValidator($attribute)
 {
     if (!($validator = @$this->attributes[$attribute]['validate'])) {
         return null;
     }
     if ($validator instanceof Validator) {
         return $validator;
     }
     if (is_array($validator)) {
         isset($validator['class']) or $validator['class'] = FileValidator::className();
         $validator['attributes'] = $attribute;
         return $this->attributes[$attribute]['validate'] = Yii::createObject($validator);
     }
     if (is_string($validator)) {
         return $this->attributes[$attribute]['validate'] = Validator::createValidator($validator, $this->owner, $attribute);
     }
 }
 /**
  * @inheritdoc
  */
 protected function validateValue($file)
 {
     $result = parent::validateValue($file);
     return empty($result) ? $this->validateImage($file) : $result;
 }
 private function validate()
 {
     $file = $this->uploadFileInstance;
     $error = [];
     $validator = new FileValidator($this->validateOptions);
     if (!$validator->validate($file, $error)) {
         throw new Exception($error);
     }
 }
 public function fieldTypeValidation()
 {
     // Messages
     $invalidMessage = "the input value has a not valid value.";
     // Validation by Input Type
     foreach ($this->fields as $field) {
         foreach ($field as $key => $value) {
             // Text
             if ($key === "type" && $value === "text") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && trim($this->data[$field["name"]]) !== "") {
                     // A pattern can be used
                     if (isset($field["pattern"])) {
                         $regexValidator = new RegularExpressionValidator(['pattern' => $field["pattern"]]);
                         if (!$regexValidator->validate($this->data[$field["name"]], $error)) {
                             $this->addError($field["name"], $field["label"], '', $error);
                         }
                     }
                 }
             }
             // Tel
             if ($key === "type" && $value === "tel") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && trim($this->data[$field["name"]]) !== "") {
                     // A pattern can be used
                     if (isset($field["pattern"])) {
                         $regexValidator = new RegularExpressionValidator(['pattern' => $field["pattern"]]);
                         if (!$regexValidator->validate($this->data[$field["name"]], $error)) {
                             $this->addError($field["name"], $field["label"], '', $error);
                         }
                     } else {
                         // By default, the number must be a international phone number
                         $phoneValidator = new PhoneValidator();
                         if (!$phoneValidator->validate($this->data[$field["name"]], $error)) {
                             $this->addError($field["name"], $field["label"], '', $error . ' ' . Yii::t("app", "It must has a internationally-standardized format\n                                (e.g. '+1 650-555-5555')"));
                         }
                     }
                 }
             }
             // Url
             if ($key === "type" && $value === "url") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && trim($this->data[$field["name"]]) !== "") {
                     // Config validator
                     $config = [];
                     // A pattern can be used
                     if (isset($field["pattern"])) {
                         $config['pattern'] = $field["pattern"];
                     }
                     $urlValidator = new UrlValidator($config);
                     if (!$urlValidator->validate($this->data[$field["name"]], $error)) {
                         $this->addError($field["name"], $field["label"], '', $error);
                     }
                 }
             }
             // Color
             if ($key === "type" && $value === "color") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && trim($this->data[$field["name"]]) !== "") {
                     // hex color invalid
                     if (!preg_match('/^#[a-f0-9]{6}$/i', $this->data[$field["name"]])) {
                         $this->addError($field["name"], $field["label"], '', $invalidMessage . ' ' . Yii::t("app", "It must be a hexadecimal color string (e.g. '#FFFFFF')."));
                     }
                 }
             }
             // Password
             if ($key === "type" && $value === "password") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && trim($this->data[$field["name"]]) !== "") {
                     $newData = trim($this->data[$field["name"]]);
                     // Remove spaces
                     $stringValidator = new StringValidator(['min' => 6]);
                     if (!$stringValidator->validate($newData, $error)) {
                         $this->addError($field["name"], $field["label"], '', $error);
                     }
                     // A pattern can be used
                     if (isset($field["pattern"])) {
                         $regexValidator = new RegularExpressionValidator(['pattern' => $field["pattern"]]);
                         if (!$regexValidator->validate($this->data[$field["name"]], $error)) {
                             $this->addError($field["name"], $field["label"], '', $error);
                         }
                     }
                 }
             }
             // Email
             if ($key === "type" && $value === "email") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && trim($this->data[$field["name"]]) !== "") {
                     // Config email validator
                     $config = [];
                     // A pattern can be used
                     if (isset($field["pattern"])) {
                         $config['pattern'] = $field["pattern"];
                     }
                     // Whether to check if email's domain exists and has either an A or MX record.
                     // Be aware that this check can fail due temporary DNS problems
                     // even if the email address is valid and an email would be deliverable
                     if (isset($field["data-check-dns"])) {
                         $config['checkDNS'] = true;
                     }
                     // Validate multiple emails separated by commas
                     if (isset($field["multiple"])) {
                         // Removes spaces
                         $emails = str_replace(" ", "", $this->data[$field["name"]]);
                         // Array of emails
                         $emails = explode(",", $emails);
                         if (count($emails) > 1) {
                             $config['message'] = Yii::t('app', '{attribute} has a invalid email format: Please use a comma to separate multiple email addresses.');
                         }
                         // Validate only one email address
                         $emailValidator = new EmailValidator($config);
                         foreach ($emails as $email) {
                             if (!$emailValidator->validate($email, $error)) {
                                 $this->addError($field["name"], $field["label"], '', $error);
                             }
                         }
                     } else {
                         // Validate only one email address
                         $emailValidator = new EmailValidator($config);
                         if (!$emailValidator->validate($this->data[$field["name"]], $error)) {
                             $this->addError($field["name"], $field["label"], '', $error);
                         }
                     }
                 }
             }
             // Radio
             if ($key === "type" && $value === "radio") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && !empty($this->data[$field["name"]])) {
                     // If no values or if the received data does not match with the form data
                     if (empty($this->radioValues) || !in_array($this->data[$field["name"]], $this->radioValues)) {
                         $this->addError($field["name"], $field["groupLabel"], '', $invalidMessage);
                     }
                 }
             }
             // Checkbox
             if ($key === "type" && $value === "checkbox") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && !empty($this->data[$field["name"]])) {
                     // If no values or if the received data does not match with the form data
                     foreach ($this->data[$field["name"]] as $labelChecked) {
                         if (empty($this->checkboxValues) || !in_array($labelChecked, $this->checkboxValues)) {
                             $this->addError($field["name"], $field["groupLabel"], '', $invalidMessage);
                         }
                     }
                 }
             }
             // Select List
             if ($key === "tagName" && $value === "select") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && !empty($this->data[$field["name"]])) {
                     // If no labels or if the received data does not match with the form data
                     foreach ($this->data[$field["name"]] as $optionSelected) {
                         if (empty($this->optionValues) || !in_array($optionSelected, $this->optionValues)) {
                             $this->addError($field["name"], $field["label"], '', $invalidMessage);
                         }
                     }
                 }
             }
             // Number & Range
             if ($key === "type" && $value === "number" || $key === "type" && $value === "range") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && trim($this->data[$field["name"]]) !== "") {
                     // Config number validator
                     $config = [];
                     // Min Number Validation (Minimum value required)
                     if (isset($field["min"])) {
                         $config['min'] = $field["min"];
                     }
                     // Max Number Validation (Maximum value required)
                     if (isset($field["max"])) {
                         $config['max'] = $field["max"];
                     }
                     // Only Integer Validation (Whether the attribute value can only be an integer)
                     if (isset($field["data-integer-only"])) {
                         $config['integerOnly'] = true;
                     }
                     // Pattern to Validate only Integer Numbers (The regular expression for matching integers)
                     if (isset($field["data-integer-pattern"])) {
                         $config['integerPattern'] = $field["data-integer-pattern"];
                     }
                     // Pattern to Validate the Number (The regular expression for matching numbers)
                     if (isset($field["data-number-pattern"])) {
                         $config['numberPattern'] = $field["data-number-pattern"];
                     }
                     $numberValidator = new NumberValidator($config);
                     if (!$numberValidator->validate($this->data[$field["name"]], $error)) {
                         $this->addError($field["name"], $field["label"], '', $error);
                     }
                 }
             }
             // Date & DateTime & Time & Month & Week
             if ($key === "type" && $value === "date" || $key === "type" && $value === "datetime-local" || $key === "type" && $value === "time" || $key === "type" && $value === "month" || $key === "type" && $value === "week") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && trim($this->data[$field["name"]]) !== "") {
                     // DateValidator Configuration array
                     $config = [];
                     // Date Format by default
                     $format = "Y-m-d";
                     // Change Format
                     if ($value === "datetime-local") {
                         // DateTime Format
                         $format = "Y-m-d\\TH:i:s";
                     } elseif ($value === "time") {
                         // Time Format
                         $format = "i:s";
                     } elseif ($value === "month") {
                         // Month Format
                         $format = "Y-m";
                     } elseif ($value === "week") {
                         // First, validate by regular expression
                         $regexValidator = new RegularExpressionValidator(['pattern' => "/\\d{4}-W\\d{2}/"]);
                         if (!$regexValidator->validate($this->data[$field["name"]], $error)) {
                             $this->addError($field["name"], $field["label"], '', $error);
                         }
                         // Next, convert to date, to dateValidator (min / max)
                         if (isset($field["min"])) {
                             $config['tooSmall'] = Yii::t("app", "{attribute} must be no less than {weekMin}.", ['weekMin' => $field["min"]]);
                             $field["min"] = date("Y-m-d", strtotime($field["min"]));
                         }
                         if (isset($field["max"])) {
                             $config['tooBig'] = Yii::t("app", "{attribute} must be no greater than {weekMax}.", ['weekMax' => $field["max"]]);
                             $field["max"] = date("Y-m-d", strtotime($field["max"]));
                         }
                         $this->data[$field["name"]] = date("Y-m-d", strtotime($this->data[$field["name"]]));
                     }
                     // Add PHP format
                     $config['format'] = "php:" . $format;
                     // Add Min Date Validation (The value must be later than this option)
                     if (isset($field["min"])) {
                         $config['min'] = $field["min"];
                     }
                     // Add Max Date Validation (The value must be earlier than this option)
                     if (isset($field["max"])) {
                         $config['max'] = $field["max"];
                     }
                     $dateValidator = new DateValidator($config);
                     if (!$dateValidator->validate($this->data[$field["name"]], $error)) {
                         $this->addError($field["name"], $field["label"], '', $error);
                     }
                 }
             }
             // File
             if ($key === "type" && $value === "file") {
                 // Only when the $_FILES name value is not empty
                 if (isset($field["name"]) && isset($_FILES[$field["name"]]['name']) && !empty($_FILES[$field["name"]]['name'])) {
                     // Config FileValidator
                     $config = [];
                     // File type validation
                     // Note that you should enable fileinfo PHP extension.
                     if (isset($field["accept"]) && extension_loaded('fileinfo')) {
                         // Removes dots
                         $extensions = str_replace(".", "", $field["accept"]);
                         // Removes spaces
                         $extensions = str_replace(" ", "", $extensions);
                         $config['extensions'] = explode(",", $extensions);
                     }
                     // File Min Size validation
                     if (isset($field["data-min-size"])) {
                         // Removes dots
                         $config['minSize'] = (int) $field["data-min-size"];
                     }
                     // File Min Size validation
                     if (isset($field["data-max-size"])) {
                         // Removes dots
                         $config['maxSize'] = (int) $field["data-max-size"];
                     }
                     $file = UploadedFile::getInstanceByName($field["name"]);
                     $fileValidator = new FileValidator($config);
                     if (!$fileValidator->validate($file, $error)) {
                         $this->addError($field["name"], $field["label"], '', $error);
                     }
                 }
             }
         }
     }
 }
 /**
  * Returns default context's validators configuration. This method may be
  * overrided in subclasses.
  * @return array default config for [[getValidators()]].
  * This value will be used in [[getValidators()]] if 'validators' property was not set.
  */
 protected function defaultValidators()
 {
     return [FileValidator::className()];
 }
 /**
  * @inheritdoc
  */
 protected function getClientOptions($model, $attribute)
 {
     $options = parent::getClientOptions($model, $attribute);
     $label = $model->getAttributeLabel($attribute);
     if ($this->minDimension !== null) {
         $options['minDimension'] = $this->minDimension;
         $options['underDimension'] = Yii::$app->getI18n()->format($this->underDimension, ['attribute' => $label, 'limit' => $this->minDimension], Yii::$app->language);
     }
     if ($this->maxDimension !== null) {
         $options['maxDimension'] = $this->maxDimension;
         $options['overDimension'] = Yii::$app->getI18n()->format($this->overDimension, ['attribute' => $label, 'limit' => $this->maxDimension], Yii::$app->language);
     }
     return $options;
 }
 /**
  * @throws \yii\base\InvalidConfigException
  */
 protected function addValidator()
 {
     unset($this->validator['maxFiles']);
     /* @var $validator \yii\validators\FileValidator|\yii\validators\ImageValidator */
     $validator = \Yii::createObject(array_merge(['class' => $this->image ? \yii\validators\ImageValidator::className() : \yii\validators\FileValidator::className(), 'attributes' => [$this->attribute]], $this->validator));
     $this->owner->getValidators()->offsetSet($this->getValidatorIndex(), $validator);
 }
 /**
  * @param UploadedFile $file
  * @return array|null
  */
 protected function validateUploadedFile(UploadedFile $file)
 {
     $baseValidation = parent::validateValue($file);
     if (!empty($baseValidation)) {
         return $baseValidation;
     }
 }