Creates a validator object.
public static createValidator ( string | Closure $type, |
||
$type | string | Closure | the validator type. This can be either: * a built-in validator name listed in [[builtInValidators]]; * a method name of the model class; * an anonymous function; * a validator class name. |
$model | the data model to be validated. | |
$attributes | array | string | list of attributes to be validated. This can be either an array of the attribute names or a string of comma-separated attribute names. |
$params | array | initial values to be applied to the validator properties. |
리턴 | the validator |
public function validateEndpoint() { $url = $this->baseUrl . $this->endpoint; $validator = Validator::createValidator('url', $this, []); if ($validator->validate($url, $error)) { // Crop fragment if (($pos = strpos($this->endpoint, '#')) !== false) { $this->endpoint = substr($this->endpoint, 0, $pos); } // Crop query if (($pos = strpos($this->endpoint, '?')) !== false) { $this->endpoint = substr($this->endpoint, 0, $pos); } // Parse params $query = parse_url($url, PHP_URL_QUERY); if (trim($query) !== '') { foreach (explode('&', $query) as $couple) { list($key, $value) = explode('=', $couple, 2) + [1 => '']; $this->queryKeys[] = urldecode($key); $this->queryValues[] = urldecode($value); $this->queryActives[] = true; } } } else { $this->addError('endpoint', $error); } }
public function attach($owner) { parent::attach($owner); if (in_array($owner->scenario, $this->scenarios)) { $fileValidator = Validator::createValidator('file', $this->owner, $this->provider->attributeName, ['types' => $this->provider->fileTypes]); $owner->validators[] = $fileValidator; } }
/** * @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); }
/** * 各类型上传文件验证 * @param $attribute * @param $params */ public function checkFile($attribute, $params) { // 按照类型 验证上传 switch ($this->type) { case Media::TYPE_IMAGE: $rule = [[$attribute], 'file', 'skipOnEmpty' => false, 'extensions' => 'jpg', 'maxSize' => 1048576]; // 1MB break; case Media::TYPE_THUMB: $rule = [[$attribute], 'file', 'skipOnEmpty' => false, 'extensions' => 'jpg', 'maxSize' => 524288]; // 64KB break; case Media::TYPE_VOICE: $rule = [[$attribute], 'file', 'skipOnEmpty' => false, 'extensions' => 'amr, mp3', 'maxSize' => 2097152]; // 2MB break; case Media::TYPE_VIDEO: $rule = [[$attribute], 'file', 'skipOnEmpty' => false, 'extensions' => 'mp4', 'maxSize' => 10485760]; // 10MB break; default: return; } $validator = Validator::createValidator($rule[1], $this, (array) $rule[0], array_slice($rule, 2)); $validator->validateAttributes($this); }
/** * @inheritdoc */ public function attach($owner) { parent::attach($owner); $validators = $owner->validators; $validator = Validator::createValidator('safe', $owner, array_keys($this->attributes)); $validators->append($validator); }
/** * @inheritdoc */ public function attach($owner) { parent::attach($owner); if (!is_array($this->attributes) || empty($this->attributes)) { throw new InvalidParamException('Invalid or empty attributes array.'); } else { foreach ($this->attributes as $attribute => $config) { if (!isset($config['path']) || empty($config['path'])) { throw new InvalidParamException('Path must be set for all attributes.'); } if (!isset($config['tempPath']) || empty($config['tempPath'])) { throw new InvalidParamException('Temporary path must be set for all attributes.'); } if (!isset($config['url']) || empty($config['url'])) { $config['url'] = $this->publish($config['path']); } $this->attributes[$attribute]['path'] = FileHelper::normalizePath(Yii::getAlias($config['path'])) . DIRECTORY_SEPARATOR; $this->attributes[$attribute]['tempPath'] = FileHelper::normalizePath(Yii::getAlias($config['tempPath'])) . DIRECTORY_SEPARATOR; $this->attributes[$attribute]['url'] = rtrim($config['url'], '/') . '/'; $validator = Validator::createValidator('string', $this->owner, $attribute); $this->owner->validators[] = $validator; unset($validator); } } }
/** * @inheritdoc */ public function attach($owner) { parent::attach($owner); $validators = $owner->validators; foreach ($this->rules as $rule) { if ($rule instanceof Validator) { $validators->append($rule); $this->validators[] = $rule; // keep a reference in behavior } elseif (is_array($rule) && isset($rule[0], $rule[1])) { // attributes, validator type $validator = Validator::createValidator($rule[1], $owner, (array) $rule[0], array_slice($rule, 2)); $validators->append($validator); $this->validators[] = $validator; // keep a reference in behavior } else { throw new InvalidConfigException('Invalid validation rule: a rule must specify both attribute names and validator type.'); } } $owner->on(ActiveRecord::EVENT_BEFORE_INSERT, function () { $this->saveRelatedDir($this->txt, $this->id_field, $this->name_field, $this->classDir); }); $owner->on(ActiveRecord::EVENT_BEFORE_UPDATE, function () { $this->saveRelatedDir($this->txt, $this->id_field, $this->name_field, $this->classDir); }); }
/** * @inheritdoc */ public function attach($owner) { parent::attach($owner); $validators = $this->owner->getValidators(); $validator = Validator::createValidator('safe', $this->owner, 'template_id'); $validators->append($validator); }
public function attach($owner) { parent::attach($owner); $validators = $owner->validators; $validator = Validator::createValidator('safe', $owner, ['singleImageArray']); $validators->append($validator); }
public function attach($owner) { parent::attach($owner); $validators = $owner->validators; $validatorInt = Validator::createValidator('integer', $owner, ['create_user_id', 'update_user_id']); $validatorSafe = Validator::createValidator('safe', $owner, ['created', 'updated']); $validators->append($validatorInt); $validators->append($validatorSafe); }
/** * @inheritdoc */ public function init() { parent::init(); if ($this->message === null) { $this->message = Yii::t('validator', '{attribute} must be an array', ['attribute' => $attribute]); } if ($this->validator !== null) { $this->_validator = Validator::createValidator($this->validator[1], null, null, array_slice($this->validator, 2)); } }
/** * Add safe validators for virtual attributes if there are not rules for them * * @param \yii\base\Component $owner */ public function attach($owner) { parent::attach($owner); foreach ($this->mlGetAttributes() as $attribute) { $validators = $this->owner->getActiveValidators($attribute); if (empty($validators)) { $this->owner->getValidators()->append(Validator::createValidator('string', $this->owner, $attribute)); } } }
/** * @inheritdoc */ public function attach($owner) { parent::attach($owner); if ($this->ownerType !== false && $this->ownerType === null) { $this->ownerType = $owner::className(); } $validators = $this->owner->getValidators(); $validator = Validator::createValidator('im\\base\\validators\\RelationValidator', $this->owner, ['meta']); $validators->append($validator); }
/** * Добавляем дополнительные валидаторы * в зависимости от типа записи */ public function beforeValidate() { switch ($this->type) { case 7: // Дата $this->validators[] = Validator::createValidator('string', $this, 'value'); break; } return true; }
/** * Initializes this behavior by setting its properties and registering * these properties as additional validators in the [[owner]]. */ public function init() { $this->owner->validators[] = Validator::createValidator('required', $this->owner, 'menu_id', ['message' => Yii::t('cms', 'Please select a menu')]); $this->owner->validators[] = Validator::createValidator('string', $this->owner, ['type', 'brand'], ['max' => 255]); if (!empty($this->owner->content)) { $properties = Json::decode($this->owner->content); $this->menu_id = $properties['menu_id']; $this->type = $properties['type']; $this->brand = $properties['brand']; } }
/** * Initializes this behavior. */ public function init() { $this->owner->validators[] = Validator::createValidator('required', $this->owner, 'category_id', ['message' => Yii::t('cms', 'Please select a category')]); $this->owner->validators[] = Validator::createValidator('string', $this->owner, ['order_by', 'order_direction', 'author_editor', 'date_displayed', 'author_editor_text', 'date_displayed_text']); $this->owner->validators[] = Validator::createValidator('integer', $this->owner, ['max_pages']); if (!empty($this->owner->content)) { $properties = Json::decode($this->owner->content); foreach ($properties as $key => $value) { $this->{$key} = $value; } } }
/** * @inheritdoc */ public function afterFind() { if (!empty($this->rules) && is_array(json_decode($this->rules, true))) { foreach (json_decode($this->rules) as $rule) { $validatorName = $rule[0]; unset($rule[0]); $this->validators[] = Validator::createValidator($validatorName, $this, 'value', $rule); } } else { $this->validators[] = Validator::createValidator('string', $this, 'value', []); } }
/** * Init values of attributes */ protected function initAttributeValues() { $attributes = $this->getAttributesDetails(); foreach ($attributes as $attribute) { $this->{$attribute->field} = Yii::$app->settings->getFromDB($attribute->group, $attribute->key, $attribute->language); } foreach ($this->rules() as $rule) { if (is_array($rule) && isset($rule[0], $rule[1]) && $rule[1] == 'default') { // attributes, validator type $validator = Validator::createValidator($rule[1], $this, (array) $rule[0], array_slice($rule, 2)); $validator->validateAttribute($this, $rule[0]); } } }
/** * */ protected function addRules() { $this->owner->validators[] = Validator::createValidator('default', $this->owner, ['position', 'level'], ['value' => 0]); $this->owner->validators[] = Validator::createValidator('integer', $this->owner, ['parent', 'position', 'level']); $this->owner->validators[] = Validator::createValidator('validateParentPath', $this->owner, ['parent']); $this->owner->validators[] = Validator::createValidator('required', $this->owner, ['alias']); $this->owner->validators[] = Validator::createValidator('string', $this->owner, ['alias'], ['max' => 255]); $this->owner->validators[] = Validator::createValidator('unique', $this->owner, ['alias'], ['targetAttribute' => ['alias', 'level', 'parent']]); if ($this->useFullAlias === true) { $this->owner->validators[] = Validator::createValidator('string', $this->owner, ['full_alias'], ['max' => 255]); $this->owner->validators[] = Validator::createValidator('unique', $this->owner, ['full_alias']); $this->owner->validators[] = Validator::createValidator('required', $this->owner, ['full_alias']); } }
public function beforeValidate($event) { /** @var ActiveRecord $model */ $model = $this->owner; if ($model->{$this->fileInputName} instanceof UploadedFile) { $file = $model->{$this->fileInputName}; } else { $file = UploadedFile::getInstance($model, $this->fileInputName); } if ($file && $file->name) { $model->{$this->fileInputName} = $file; $validator = Validator::createValidator('file', $model, $this->fileInputName, ['extensions' => $this->extensions]); $validator->validateAttribute($model, $this->fileInputName); } }
/** * Add safe validators for virtual attributes if there are not rules for them * * @param \yii\base\Component $owner */ public function attach($owner) { parent::attach($owner); $singletonKey = 'validators_created_' . get_class($this->owner); $validatorsCreated = Singleton::getData($singletonKey); if (!$validatorsCreated) { foreach ($this->mlGetAttributes() as $attribute) { $validators = $this->owner->getActiveValidators($attribute); if (empty($validators)) { $this->owner->getValidators()->append(Validator::createValidator('string', $this->owner, $attribute)); } } Singleton::setData($singletonKey, true); } }
protected function loadEavAttributes() { if (!$this->isAttributesLoaded) { $modelTable = EavEntityModel::tableName(); $entityTable = EavEntity::tableName(); $attributeTable = EavAttribute::tableName(); $entityToAttributeTable = '{{%eav_entity_attribute}}'; $attributes = EavAttribute::find()->innerJoin($entityToAttributeTable, "{$attributeTable}.id = {$entityToAttributeTable}.attribute_id")->innerJoin($entityTable, "{$entityToAttributeTable}.entity_id = {$entityTable}.id")->innerJoin($modelTable, "{$entityTable}.model_id = {$modelTable}.id")->andWhere(["{$modelTable}.entity_model" => $this->ownerClassName])->andWhere(["{$entityTable}.category_id" => $this->getEavCatgoryId()])->orderBy(['order' => SORT_DESC])->all(); $validators = $this->owner->getValidators(); foreach ($attributes as $attribute) { $this->eavAttributes->{$attribute['name']} = $attribute; $validators[] = \yii\validators\Validator::createValidator('safe', $this->owner, [$attribute['name']], []); } $this->isAttributesLoaded = true; } }
/** * @inheritdoc */ public function attach($owner) { parent::attach($owner); $validators = $owner->validators; foreach ($this->imageRules() as $rule) { if ($rule instanceof Validator) { $validators->append($rule); $this->validators[] = $rule; } elseif (is_array($rule) && isset($rule[0], $rule[1])) { $validator = Validator::createValidator($rule[1], $owner, (array) $rule[0], array_slice($rule, 2)); $validators->append($validator); $this->validators[] = $validator; } else { throw new InvalidConfigException('Invalid validation rule: a rule must specify both attribute names and validator type.'); } } }
public function testCreatePostSetImages() { $post = new Post(); $post->validators[] = Validator::createValidator('safe', $post, ['imageNames']); $post->attachBehavior('target-images', ['class' => Target::className(), 'targetAttribute' => 'imageNames', 'targetRelation' => 'images', 'delimiter' => false, 'getItem' => function ($name, $class) { return new $class(['name' => $name]); }]); $post->setAttributes(['title' => 'New post title', 'body' => 'New post body', 'imageNames' => ['img1.jpg', 'img2.jpg', 'img3.jpg']]); $this->assertTrue($post->save()); $this->assertEquals(['img1.jpg', 'img2.jpg', 'img3.jpg'], $post->imageNames); $images = array_map(function ($value) { /** @var Image $value */ return $value->toArray(); }, $post->images); $new_images = [['id' => 6, 'name' => 'img1.jpg', 'post_id' => 4], ['id' => 7, 'name' => 'img2.jpg', 'post_id' => 4], ['id' => 8, 'name' => 'img3.jpg', 'post_id' => 4]]; $this->assertEquals($new_images, $images); }
/** * Initializes this behavior by setting its properties and registering * these properties as additional validators in the [[owner]]. */ public function init() { $this->owner->validators[] = Validator::createValidator('required', $this->owner, 'receiver'); $this->owner->validators[] = Validator::createValidator('email', $this->owner, 'receiver'); $this->owner->validators[] = Validator::createValidator('string', $this->owner, ['successMessage', 'redirectTo']); $this->owner->validators[] = Validator::createValidator(function ($attribute, $params) { foreach ($this->fields as $field) { if (!is_numeric($field['show']) || !is_numeric($field['required'])) { $this->owner->addError($attribute, 'Invalid data type'); } } }, $this->owner, 'fields'); if (!empty($this->owner->content)) { $properties = Json::decode($this->owner->content); foreach ($properties as $key => $value) { $this->{$key} = $value; } } }
public function validateEndpoint() { $url = 'http://example.com/' . $this->endpoint; $validator = Validator::createValidator('url', $this, []); if ($validator->validate($url, $error)) { // Crop fragment if (($pos = strpos($this->endpoint, '#')) !== false) { $this->endpoint = substr($this->endpoint, 0, $pos); } // Crop query if (($pos = strpos($this->endpoint, '?')) !== false) { $this->endpoint = substr($this->endpoint, 0, $pos); } // Convert query string into params $query = trim(parse_url($url, PHP_URL_QUERY)); $this->parseQuery($query, $this->queryKeys, $this->queryValues, $this->queryActives); } else { $this->addError('endpoint', $error); } }
/** * @param array $data * @param array $rules * @param \yii\db\ActiveRecord|boolean $origin * @return DynamicModel * @throws InvalidConfigException * @see DynamicModel::validateData */ public static function validateModelData(array $data, $rules = [], $origin = false) { $model = new static($data); $model->origin = $origin; $model->setScenario($origin->scenario); if (!empty($rules)) { $validators = $model->getValidators(); foreach ($rules as $rule) { if ($rule instanceof Validator) { $validators->append($rule); } elseif (is_array($rule) && isset($rule[0], $rule[1])) { // attributes, validator type $validator = Validator::createValidator($rule[1], $model, (array) $rule[0], array_slice($rule, 2)); $validators->append($validator); } else { throw new InvalidConfigException('Invalid validation rule: a rule must specify both attribute names and validator type.'); } } } $model->validate(); return $model; }
protected function prepareValidators() { $rules = $this->rules(); $validators = $this->getValidators(); $newValidators = []; $safeAttributes = []; foreach ($rules as $rule) { if ($rule instanceof Validator) { $rule_attributes = (array) $rule->attributes[0]; $safeAttributes = array_merge($safeAttributes, $rule_attributes); $rule->attributes = $this->populateAttributes($rule_attributes); $newValidators[] = $rule; } elseif (is_array($rule) && isset($rule[0], $rule[1])) { $attributes = (array) $rule[0]; $safeAttributes = array_merge($safeAttributes, $attributes); $validator = Validator::createValidator($rule[1], $this, $this->populateAttributes($attributes), array_slice($rule, 2)); $newValidators[] = $validator; } else { throw new InvalidConfigException('Invalid validation rule: a rule must specify both attribute names and validator type.'); } } $newValidators[] = Validator::createValidator('safe', $this, array_unique($safeAttributes)); $validators->exchangeArray($newValidators); }
/** * Creates validator objects based on the validation rules specified in [[rules()]]. * Unlike [[getValidators()]], each time this method is called, a new list of validators will be returned. * @return ArrayObject validators * @throws InvalidConfigException if any validation rule configuration is invalid */ public function createValidators() { $validators = new ArrayObject(); foreach ($this->rules() as $rule) { if ($rule instanceof Validator) { $validators->append($rule); } elseif (is_array($rule) && isset($rule[0], $rule[1])) { // attributes, validator type $validator = Validator::createValidator($rule[1], $this, (array) $rule[0], array_slice($rule, 2)); $validators->append($validator); } else { throw new InvalidConfigException('Invalid validation rule: a rule must specify both attribute names and validator type.'); } } return $validators; }
/** * Adds a validation rule to this model. * You can also directly manipulate [[validators]] to add or remove validation rules. * This method provides a shortcut. * @param string|array $attributes the attribute(s) to be validated by the rule * @param mixed $validator the validator for the rule.This can be a built-in validator name, * a method name of the model class, an anonymous function, or a validator class name. * @param array $options the options (name-value pairs) to be applied to the validator * @return $this the model itself */ public function addRule($attributes, $validator, $options = []) { $validators = $this->getValidators(); $validators->append(Validator::createValidator($validator, $this, (array) $attributes, $options)); return $this; }