Since: 2.0
Author: Qiang Xue (qiang.xue@gmail.com)
Inheritance: extends Validator
 /**
  * (non-PHPdoc)
  * @see \yii\validators\Validator::validateAttributes()
  */
 public function validateAttributes($model, $attributes = null)
 {
     //prepare attributes
     if (is_array($attributes)) {
         $attributes = array_intersect($this->attributes, $attributes);
     } else {
         $attributes = $this->attributes;
     }
     //validate all attributes with the required validator
     $reqVal = new RequiredValidator();
     $numOk = 0;
     $labelList = [];
     foreach ($attributes as $attr) {
         $labelList[] = $model->getAttributeLabel($attr);
         if ($reqVal->validate($model->{$attr})) {
             $numOk++;
         }
     }
     //check if ok or add error message
     if ($numOk < $this->numRequired) {
         //prepare message
         $msg = Yii::t('yii', $this->message, ['num' => $this->numRequired, 'num2' => $this->numRequired, 'attributes' => implode(', ', $labelList), 'errorAttribute' => $this->errorAttribute]);
         //decide where to add the message
         if ($this->errorAttribute !== null) {
             $this->addError($model, $this->errorAttribute, $msg);
         } else {
             foreach ($this->attributes as $attr) {
                 $this->addError($model, $attr, $msg);
             }
         }
     }
 }
 /**
  * @param ActiveRecord $owner
  */
 public function attach($owner)
 {
     parent::attach($owner);
     // Применяем конфигурационные опции
     foreach ($this->imageConfig as $key => $value) {
         $var = '_' . $key;
         $this->{$var} = $value;
     }
     // Вычисляем корень сайта
     if (empty($this->_rootPathAlias)) {
         $savePathParts = explode('/', $this->_savePathAlias);
         // Удаляем последнюю часть
         unset($savePathParts[count($savePathParts - 1)]);
         // Объединяем все части обратно
         $this->_rootPathAlias = implode('/', $savePathParts);
     }
     // Добавляем валидатор require
     if ($this->_imageRequire) {
         $owner->validators->append(Validator::createValidator(RequiredValidator::className(), $owner, $this->_imageAttribute));
     }
     // Подключаем валидатор изображения
     $validatorParams = array_merge(['extensions' => $this->_fileTypes, 'maxSize' => $this->_maxFileSize, 'skipOnEmpty' => true, 'tooBig' => 'Изображение слишком велико, максимальный размер: ' . floor($this->_maxFileSize / 1024 / 1024) . ' Мб'], $this->_imageValidatorParams);
     $validator = Validator::createValidator(ImageValidator::className(), $owner, $this->_imageAttribute, $validatorParams);
     $owner->validators->append($validator);
 }
 public function testValidateAttribute()
 {
     // empty req-value
     $val = new RequiredValidator();
     $m = FakedValidationModel::createWithAttributes(['attr_val' => null]);
     $val->validateAttribute($m, 'attr_val');
     $this->assertTrue($m->hasErrors('attr_val'));
     $this->assertTrue(stripos(current($m->getErrors('attr_val')), 'blank') !== false);
     $val = new RequiredValidator(['requiredValue' => 55]);
     $m = FakedValidationModel::createWithAttributes(['attr_val' => 56]);
     $val->validateAttribute($m, 'attr_val');
     $this->assertTrue($m->hasErrors('attr_val'));
     $this->assertTrue(stripos(current($m->getErrors('attr_val')), 'must be') !== false);
     $val = new RequiredValidator(['requiredValue' => 55]);
     $m = FakedValidationModel::createWithAttributes(['attr_val' => 55]);
     $val->validateAttribute($m, 'attr_val');
     $this->assertFalse($m->hasErrors('attr_val'));
 }
Example #4
0
 protected function validateValue($value)
 {
     $badStructure = 'Неправильная структура данных.';
     try {
         $decoded = Json::decode($value);
     } catch (InvalidParamException $e) {
         return [$badStructure];
     }
     if (!array_key_exists(0, $decoded) || !array_key_exists(1, $decoded)) {
         return [$badStructure];
     }
     $state = $decoded[0];
     $value = $decoded[1];
     if (!in_array($state, [ComboWidget::STATE_LIST, ComboWidget::STATE_TEXT])) {
         return [$badStructure];
     }
     if ($this->required === true) {
         $validator = new RequiredValidator();
         $error = null;
         if (!$validator->validate($value, $error)) {
             return [$error];
         }
     }
     if ($value === null || $value === '') {
         $this->_targetValue = null;
         return null;
     }
     if ($state === ComboWidget::STATE_LIST) {
         $this->_targetValue = ['id' => (int) $value];
         return null;
     }
     if ($state === ComboWidget::STATE_TEXT) {
         $value = StringHelper::squeezeLine($value);
         $validator = new NazvanieValidator();
         $error = null;
         if (!$validator->validate($value, $error)) {
             return [$error];
         }
         $this->_targetValue = ['nazvanie' => $value];
         return null;
     }
     return [$badStructure];
 }
 public function init()
 {
     parent::init();
     //todo using strict options
     $this->when = function () {
         $oth_val = $this->targetModel->{$this->targetAttribute};
         return $this->isEmpty(is_string($oth_val) ? trim($oth_val) : $oth_val);
     };
     //todo using strict options
     $id = Html::getInputId($this->targetModel, $this->targetAttribute);
     $this->whenClient = "function(){return \$('#{$id}').prop('disabled');}";
 }
Example #6
0
 /**
  * Validate 'value' attribute against of 'value_type'.
  */
 public function validateValue($attribute, $params = [])
 {
     if ($this->required) {
         $required = Yii::createObject(['class' => \yii\validators\RequiredValidator::className(), 'message' => Yii::t('app', '{label} is required.', ['label' => $this->title])]);
         if (!$required->validate($this->{$attribute})) {
             $this->addError($attribute, $required->message);
             return;
         }
     } else {
         $value = $this->{$attribute};
         if ($value === null || $value === '') {
             return;
         }
     }
     switch ($this->value_type) {
         case static::TYPE_INT:
             $args = ['class' => NumberValidator::className(), 'integerOnly' => true, 'message' => 'Not an integer'];
             break;
         case static::TYPE_NUM:
             $args = ['class' => NumberValidator::className(), 'message' => 'Not a number'];
             break;
         case static::TYPE_EMAIL:
             $args = ['class' => EmailValidator::className(), 'message' => 'Not a valid email'];
             break;
         case static::TYPE_URL:
             $args = ['class' => UrlValidator::className(), 'message' => 'Not a valid url'];
             break;
         case static::TYPE_SWITCH:
             $args = ['class' => BooleanValidator::className(), 'message' => 'Must be boolean value'];
             break;
         case static::TYPE_TEXT:
         case static::TYPE_EDITOR:
         case static::TYPE_PASSWORD:
             $args = ['class' => StringValidator::className()];
             break;
         case static::TYPE_SELECT:
             $args = ['class' => RangeValidator::className(), 'range' => array_keys($this->options), 'message' => 'Invalid value'];
             break;
         default:
             throw new InvalidParamException('Unknown config type: ' . $this->value_type);
     }
     $validator = Yii::createObject($args);
     if (!$validator->validate($this->{$attribute})) {
         $this->addError($attribute, $validator->message);
     } else {
         $this->castType();
     }
 }
Example #7
0
 /**
  * @return array
  */
 public function rules()
 {
     return [['parent_id', 'validateParent'], ['label', StringValidator::className()], ['label', RequiredValidator::className()], ['path', StringValidator::className()], ['status', BooleanValidator::className()], ['order_num', NumberValidator::className()]];
 }
 /**
  * @inheritdoc
  */
 public function init()
 {
     parent::init();
     $this->_validated = new SplObjectStorage();
 }
 public function validateSchedule($attribute)
 {
     $requiredValidator = new RequiredValidator();
     foreach ($this->{$attribute} as $index => $row) {
         $error = null;
         $requiredValidator->validate($row['priority'], $error);
         if (!empty($error)) {
             $key = $attribute . '[' . $index . '][priority]';
             $this->addError($key, $error);
         }
     }
 }
 public function validateSchedule($attribute)
 {
     $requiredValidator = new RequiredValidator();
     foreach ($this->{$attribute} as $index => $row) {
         $error = null;
         foreach (['user_id', 'priority'] as $name) {
             $error = null;
             $value = isset($row[$name]) ? $row[$name] : null;
             $requiredValidator->validate($value, $error);
             if (!empty($error)) {
                 $key = $attribute . '[' . $index . '][' . $name . ']';
                 $this->addError($key, $error);
             }
         }
     }
 }
Example #11
0
 /**
  * The required validation works in 3 steps:
  * 1. Get all required fields that are not in the submission (data and files). If there are, at least one,
  *    the validation fail.
  * 2. Get all required files. If a required file if not in the global $_FILES, the validation fail.
  * 3. Get all required fields that pass the last steps, and validates them with a RequiredValidator.
  */
 public function requiredFieldsValidation()
 {
     // Messages
     $requiredMessage = Yii::t('app', 'the input value is required.');
     // Compares requiredLabels keys against data and files keys, and returns the difference
     // All requiredLabel that are not in the submission data and file uploads
     $requiredFields = array_diff_key($this->requiredLabels, $this->data, $_FILES);
     // If exist a requiredField, add a required error
     // Useful to validate if a least one checkbox of a group is checked
     if (count($requiredFields) > 0) {
         foreach ($requiredFields as $name => $label) {
             $this->addError($name, $label, '', $requiredMessage);
         }
     }
     // Check all required File Inputs with $_FILES
     foreach ($this->requiredFileLabels as $name => $label) {
         if (!is_array($_FILES) || !isset($_FILES[$name]) || !isset($_FILES[$name]['name']) || empty($_FILES[$name]['name'])) {
             // If no file was upload
             $this->addError($name, $label, '', $requiredMessage);
         }
     }
     // Get all submission data, that were not in the last validations
     $data = array_diff_key($this->data, $requiredFields, $this->requiredFileLabels);
     // Filter required data
     $requiredData = array_intersect_key($data, $this->requiredLabels);
     // Check each fields item with requiredValidator
     $requiredValidator = new RequiredValidator();
     // If a field does'nt pass the validator, add a blank error
     if (count($requiredData) > 0) {
         foreach ($requiredData as $name => $value) {
             if (!$requiredValidator->validate($value, $error)) {
                 $this->addError($name, $this->requiredLabels[$name], '', $error);
             }
         }
     }
 }
Example #12
0
 public function rules()
 {
     return [[['type', 'name'], RequiredValidator::className()], [['length', 'precision', 'scale'], NumberValidator::className()], [['is_not_null', 'is_unique', 'unsigned', 'isCompositeKey'], BooleanValidator::className()], [['name'], StringValidator::className(), 'max' => 50], [['comment', 'fk_name'], StringValidator::className(), 'max' => 255], [['type'], RangeValidator::className(), 'range' => $this->getTypeList()]];
 }
 private function internalValidateAnswers($questionIndex, $answers)
 {
     $requiredValidator = new RequiredValidator();
     $error = null;
     foreach ($answers as $answerIndex => $answer) {
         $error = null;
         $value = ArrayHelper::getValue($answer, 'answer', null);
         $requiredValidator->validate($value, $error);
         if (!empty($error)) {
             $key = sprintf('questions[%d][answers][%d][answer]', $questionIndex, $answerIndex);
             $this->addError($key, $error);
         }
     }
 }