This method executes the validation rules applicable to the current [[scenario]].
The following criteria are used to determine whether a rule is currently applicable:
- the rule must be associated with the attributes relevant to the current scenario;
- the rules must be effective for the current scenario.
This method will call Model::beforeValidate and Model::afterValidate before and
after the actual validation, respectively. If Model::beforeValidate returns false,
the validation will be cancelled and Model::afterValidate will not be called.
Errors found during the validation can be retrieved via Model::getErrors,
Model::getFirstErrors and Model::getFirstError.
public validate ( array $attributeNames = null, boolean $clearErrors = true ) : boolean | ||
$attributeNames | array | list of attribute names that should be validated. If this parameter is empty, it means any attribute listed in the applicable validation rules should be validated. |
$clearErrors | boolean | whether to call [[clearErrors()]] before performing validation |
return | boolean | whether the validation is successful without any error. |
/** * Validate attribute & throw exception * * @param array $attributeNames * @param boolean $clearErrors * @param boolean $throwException * @return boolean * @throws ModelException */ public function validate($attributeNames = null, $clearErrors = true, $throwException = true) { if (!parent::validate($attributeNames, $clearErrors) && $throwException) { throw new ModelException($this, Code::GENERAL_INVALID_USER_INPUT); } return !$this->hasErrors(); }
public function validate($attributeNames = null, $clearErrors = true) { $isValid = true; foreach ($this->models as $model) { $isValid = $model->validate($attributeNames, $clearErrors) && $isValid; } return parent::validate($attributeNames, $clearErrors) && $isValid; }
/** * Upload file * * @param Model $model * @param array $attributes - Model file type attributes * @param bool $multiple * * @return array Attachment ID */ public function upload($model = null, $attributes = null, $multiple = null) { $this->prepare($model, $attributes, $multiple); if ($this->model !== null && $this->attributes && $this->model->validate()) { foreach ($this->attributes as $attribute) { if ($this->model->{$attribute}) { if (is_array($this->model->{$attribute})) { foreach ($this->model->{$attribute} as $file) { $ids[] = $this->uploadFile($file, $attribute); } } else { $ids[] = $this->uploadFile($this->model->{$attribute}, $attribute); } } } } return isset($ids) ? $ids : []; }
/** * Валидация атрибутов. * * На вход передается модель для валидации и массив значений для валидации. * Массив значений должен иметь следующий формат: * ```php * array( * '<attribute1>' => array( * array( * 'value' => <mixed>, // значение для валидации * 'isValid' => <boolean>, // true, если значение должно проходить валидацию * ), * ), * ) * ``` * * Проверяет, что атрибут либо должен проходить проверку валидации, либо не должен. * * @param Model $model проверяемая модель * @param array $attributes массив значений атрибутов для валидации */ protected function validateAttributes(Model $model, $attributes) { foreach ($attributes as $attribute => $values) { $attributeTitle = $model->getAttributeLabel($attribute); foreach ($values as $v) { $value = $v['value']; $isValid = $v['isValid']; $model->{$attribute} = $value; if ($isValid) { $message = $attributeTitle . ' validation error: ' . implode("\n", $model->getErrors($attribute)); $message .= "\nAsserting value: " . print_r($value, true); $this->assertTrue($model->validate([$attribute]), $message); } else { $message = $attributeTitle . ' must be invalid' . "\n"; $message .= 'Asserting value: ' . print_r($value, true); $this->assertFalse($model->validate([$attribute]), $message); } } } }
/** * @param Model $model * @param string $attribute */ private function readValue($model, $attribute) { $model->{$attribute} = $this->prompt(mb_convert_case($attribute, MB_CASE_TITLE, 'utf-8') . ':', ['validator' => function ($input, &$error) use($model, $attribute) { $model->{$attribute} = $input; if ($model->validate([$attribute])) { return true; } else { $error = implode(',', $model->getErrors($attribute)); return false; } }]); }
/** * @param string $prompt * @param \yii\base\Model $model * @param string $field * @param string $default * @return string */ private function readStdinUser($prompt, $model, $field, $default = '') { while (!isset($input) || !$model->validate(array($field))) { echo $prompt . ($default ? " [{$default}]" : '') . ': '; $input = trim(fgets(STDIN)); if (empty($input) && !empty($default)) { $input = $default; } $model->{$field} = $input; } return $input; }
/** * Verifies that given attribute may contains given values * @param \yii\base\Model $model * @param string $attr * @param string $specify */ public function verifyForeignKey(\yii\base\Model $model, $attr, $classname, $specify = '%s is foreign key') { $this->_verificated = $model; $pk = static::valMaxPrimaryKey($classname); $this->specify(sprintf($specify, $attr), function () use($attr, $pk) { \Codeception\Util\Debug::debug('- verifying FOREIGN KEY'); $this->_verificated->{$attr} = $pk; verify($this->_verificated->validate([$attr]))->true(); $this->_verificated->{$attr} = $pk + 1; verify($this->_verificated->validate([$attr]))->false(); }); }
public function validate($attributeNames = NULL, $clearErrors = true) { foreach ($this->_attributes as $attribute => $value) { if ($this->isSerializable($attribute)) { $data = json_decode($value, true); if (!is_array($data) || json_last_error()) { $this->addError($attribute, "Not valid json"); return false; } } } return parent::validate($attributeNames = NULL, $clearErrors = true); }
public function validate($attributes = null, $clearErrors = true) { parent::validate($attributes, $clearErrors); //每次只返回一个错误 $error = $this->getErrors(); $i = 0; foreach ($error as $key => $value) { if ($i > 0) { $this->clearErrors($key); } $i++; } return !$this->hasErrors(); }
/** * Validates a ProfileFieldType * * This is only necessary when its linked to a profileField and the profiletype * has the current type of profilefieldtype * * @return boolean */ public function validate($attributes = null, $clearErrors = true) { // Bound to a profile field? if ($this->profileField != null) { // Current Profile Field matches the selected profile field if ($this->profileField->field_type_class == get_class($this)) { return parent::validate($attributes, $clearErrors); } } return true; }
public function validate($attributeNames = null, $clearErrors= true){ $this->image=UploadedFile::getInstance($this,'image'); if(!parent::validate($attributeNames, $clearErrors)){ $_message = Auction::loggerMessageFormat('Dealer Registration not validated with following Param',$this->attributes()); Auction::error($_message); return false; } if($this->image instanceof UploadedFile){ if(!getimagesize($this->image->tempName)){ $this->addError('image','Please Upload a valid Image'); return false; } $this->trigger(Events::UPLOAD_IMAGE); } return true; }
/** * Performs the data validation. * @param Model $model * @return boolean whether the validation is successful without any error. */ protected function validateModel($model) { return $model->validate(); }
/** * Saves configuration model. Performs validation if needed. * * @param \yii\base\Model $model * @param bool $validate * @param bool $apply * @return bool */ public function saveConfigurationModel($model, $validate = true, $apply = true) { if (!$model) { return false; } if ($validate && !$model->validate()) { return false; } if ($this->modelClass) { //If modelClass is using $modelClass = $this->modelClass; //Check object and save if ($model instanceof $modelClass && $this->_keyStorage->set($this->getKey(), $model)) { //Apply new configuration if ($apply) { $this->_configuration = $model; $this->configure(); } return true; } else { return false; } } else { return $this->saveConfigurationArray($model->getAttributes(), $apply); } }
/** * @param \yii\base\Model $model * @param array $attributes * @return bool */ private function validateModel(\yii\base\Model $model, array $attributes) { $model->attributes = $attributes; if ($model->validate() !== true) { $this->errors[] = $model->getFirstErrors(); return false; } return true; }
/** * Validates one or several models and returns an error message array indexed by the attribute IDs. * This is a helper method that simplifies the way of writing AJAX validation code. * * For example, you may use the following code in a controller action to respond * to an AJAX validation request: * * ```php * $model = new Post; * $model->load($_POST); * if (Yii::$app->request->isAjax) { * Yii::$app->response->format = Response::FORMAT_JSON; * return ActiveForm::validate($model); * } * // ... respond to non-AJAX request ... * ``` * * To validate multiple models, simply pass each model as a parameter to this method, like * the following: * * ```php * ActiveForm::validate($model1, $model2, ...); * ``` * * @param Model $model the model to be validated * @param mixed $attributes list of attributes that should be validated. * If this parameter is empty, it means any attribute listed in the applicable * validation rules should be validated. * * When this method is used to validate multiple models, this parameter will be interpreted * as a model. * * @return array the error message array indexed by the attribute IDs. */ public static function validate($model, $attributes = null) { $result = []; if ($attributes instanceof Model) { // validating multiple models $models = func_get_args(); $attributes = null; } else { $models = [$model]; } /* @var $model Model */ foreach ($models as $model) { $model->validate($attributes); foreach ($model->getErrors() as $attribute => $errors) { $result[Html::getInputId($model, $attribute)] = $errors; } } return $result; }
public function validate($attributeNames = null, $clearErrors = true) { return parent::validate($attributeNames, $clearErrors); }
/** * @param null $attributeNames * @param bool $clearErrors * @return bool */ public function validate($attributeNames = null, $clearErrors = true) { if (parent::validate($attributeNames, $clearErrors)) { $this->populateSourceAttributes(); $source = $this->source; if (!$source->validate()) { if ($this->defaultAttribute && $source->hasErrors()) { $this->populateErrors($source, $this->defaultAttribute); } return false; } return true; } return false; }