/** * Validates the given data with the specified validation rules. * This method will create a DynamicModel instance, populate it with the data to be validated, * create the specified validation rules, and then validate the data using these rules. * @param array $data the data (name-value pairs) to be validated * @param array $rules the validation rules. Please refer to [[Model::rules()]] on the format of this parameter. * @return static the model instance that contains the data being validated * @throws InvalidConfigException if a validation rule is not specified correctly. */ public static function validateData(array $data, $rules = []) { /* @var $model DynamicModel */ $model = new static($data); 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; }
/** * 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; }
/** * Creates validator object based on the validation rule specified in [[rule]]. * @param Model|null $model model in which context validator should be created. * @throws \Leaps\Base\InvalidConfigException * @return Validator validator instance */ private function createEmbeddedValidator($model) { $rule = $this->rule; if ($rule instanceof Validator) { return $rule; } elseif (is_array($rule) && isset($rule[0])) { // validator type if (!is_object($model)) { $model = new Model(); // mock up context model } return Validator::createValidator($rule[0], $model, $this->attributes, array_slice($rule, 1)); } else { throw new InvalidConfigException('Invalid validation rule: a rule must be an array specifying validator type.'); } }