Validate the model before saving.

@return array
434922
public function savingValidation()
    {
        global $app;

        $this->preValidationCast();
        $this->validator = new Validator($app['translator'], $this->getDirty(), $this->getAttributeRules());

        if ($this->validator->fails()) {
            return false;
        }

        return true;
    }
646313
public function isValid()
    {
        $validators = [
            'isDateValuesIntegers',
            'isValidDayRange',
            'isValidMonthRange',
            'isValidPagumeDayRange',
            'isValidLeapDay',
        ];

        return array_reduce($validators, function ($result, $validator) {
            return $result && $this->{$validator}();
        }, true);
    }
687674
protected function beforeValidate() 
	{
		$controller = strtolower(Yii::app()->controller->id);
		$setting = BannerSetting::model()->findByPk(1, array(
			'select' => 'banner_validation, banner_file_type',
		));
		$banner_file_type = unserialize($setting->banner_file_type);
		if(empty($banner_file_type))
			$banner_file_type = array();
		
		if(parent::beforeValidate()) {
			if($this->isNewRecord)
				$this->creation_id = !Yii::app()->user->isGuest ? Yii::app()->user->id : null;
			else
				$this->modified_id = !Yii::app()->user->isGuest ? Yii::app()->user->id : null;
			
			$banner_filename = CUploadedFile::getInstance($this, 'banner_filename');
			if($banner_filename != null) {
				$extension = pathinfo($banner_filename->name, PATHINFO_EXTENSION);
				$validation = 0;
				if($setting->banner_validation == 1)
					$validation = 1;
				$fileSize = getimagesize($banner_filename->tempName);
				$bannerSize = unserialize($this->category->banner_size);
				
				if(!in_array(strtolower($extension), $banner_file_type))
					$this->addError('banner_filename', Yii::t('phrase', 'The file {name} cannot be uploaded. Only files with these extensions are allowed: {extensions}.', array(
						'{name}'=>$banner_filename->name,
						'{extensions}'=>Utility::formatFileType($banner_file_type, false),
					)));
				else {
					if($validation == 1 && !($fileSize[0] == $bannerSize['width'] && $fileSize[1] == $bannerSize['height']))
						$this->addError('banner_filename', Yii::t('phrase', 'The file {name} cannot be uploaded. ukuran banner ({file_size}) tidak sesuai dengan kategori ({banner_size})', array(
							'{name}'=>$banner_filename->name,
							'{file_size}'=>$fileSize[0].' x '.$fileSize[1],
							'{banner_size}'=>$bannerSize['width'].' x '.$bannerSize['height'],
						)));
				}
			} else {
				if($this->isNewRecord && $controller == 'o/admin')
					$this->addError('banner_filename', Yii::t('phrase', 'Banner (File) cannot be blank.'));
			}
			
			if($this->linked_i == 0)
				$this->url = '-';
			
			if(in_array(Yii::$app->formatter->asDate($this->expired_date, 'php:Y-m-d'), array('00-00-0000','01-01-1970')))
				$this->permanent_i = 1;
			
			if($this->permanent_i == 1)
				$this->expired_date = '00-00-0000';
			
			if($this->linked_i == 1 && $this->url == '-')
				$this->addError('url', Yii::t('phrase', 'URL harus dalam format hyperlink'));
			
			if($this->permanent_i != 1 && ($this->published_date != '' && $this->expired_date != '') && ($this->published_date >= $this->expired_date))
				$this->addError('expired_date', Yii::t('phrase', 'Expired lebih kecil'));
		}
		return true;
	}
153822
public function validation()
    {
        $validator = new Validation();
        $validator->add(
            'email',
            new Email([
                'field' => 'email',
                'required' => true,
            ])
        );

        $validator->add(
            'displayname',
            new PresenceOf([
                'field' => 'displayname',
                'required' => true,
            ])
        );

        $validator->add(
            'displayname',
            new Regex([
                'field' => 'displayname',
                'message' => _('Please use alphanumerics only.'),
                'pattern' => '/^[A-Za-z0-9_.-]{1,16}$/',
            ])
        );

        // Unique values
        $validator->add(
            'email',
            new Uniqueness([
                'field' => 'email',
                'message' => _('This email already has an account.'),
            ])
        );

        $validator->add(
            'displayname',
            new Uniqueness([
                'field' => 'displayname',
                'message' => _('The username is already taken.'),
            ])
        );

        return $this->validate($validator);
    }
231707
protected function beforeValidate() 
	{
		$currentAction = strtolower(Yii::app()->controller->id.'/'.Yii::app()->controller->action->id);
		
		if(parent::beforeValidate()) {
			//if($this->office_place == '' || $this->office_district == '' || $this->office_village == '') {
			if($this->office_place == '') {
				$this->addError('office_place', Yii::t('phrase', 'Office Address cannot be blank.'));
				//$this->addError('office_village', Yii::t('phrase', 'Office Village cannot be blank.'));
				//$this->addError('office_district', Yii::t('phrase', 'Office District cannot be blank.'));
			}
			
			$meta_image = CUploadedFile::getInstance($this, 'meta_image');	
			if($meta_image->name != '') {
				$extension = pathinfo($meta_image->name, PATHINFO_EXTENSION);
				if(!in_array($extension, array('bmp','gif','jpg','png')))
					$this->addError('meta_image', 'The file $image_name cannot be uploaded. Only files with these extensions are allowed: bmp, gif, jpg, png.', array('$image_name'=>$meta_image->name));
			}
			
			if($currentAction == 'meta/twitter') {
				if($this->twitter_card == 3) {
					if($this->twitter_photo_size['width'] == '')
						$this->addError('twitter_photo_size[width]', Yii::t('phrase', 'Photo Width cannot be blank.'));
					if($this->twitter_photo_size['height'] == '')
						$this->addError('twitter_photo_size[height]', Yii::t('phrase', 'Photo Height cannot be blank.'));
				}
			}
			
			$this->modified_id = Yii::app()->user->id;
		}
		return true;
	}
1277961
protected function validatePost()
    {
        $oFormValidation = Factory::service('FormValidation');

        $aRules = [
            'ref'             => 'trim',
            'state'           => 'trim|required',
            'dated'           => 'trim|required|valid_date',
            'currency'        => 'trim|required|callback__callbackValidCurrency',
            'terms'           => 'trim|is_natural',
            'customer_id'     => 'trim',
            'additional_text' => 'trim',
            'items'           => '',
        ];

        $aRulesFV = [];
        foreach ($aRules as $sKey => $sRules) {
            $aRulesFV[] = [
                'field' => $sKey,
                'label' => '',
                'rules' => $sRules,
            ];
        }

        $oFormValidation->set_rules($aRulesFV);

        $oFormValidation->set_message('required', lang('fv_required'));
        $oFormValidation->set_message('valid_date', lang('fv_valid_date'));
        $oFormValidation->set_message('is_natural', lang('fv_is_natural'));
        $oFormValidation->set_message('valid_email', lang('fv_valid_email'));

        return $oFormValidation->run($this);
    }
69649
public function validate()
	{
		// reset the error container and status
		$this->errors = array();
		$this->isValid = true;

		// validation starts, call the pre-validation callback
		$this->runCallbacks('before_validation');

		// was the upload of the file a success?
		if ($this->container['error'] == 0)
		{
			// add some filename details (pathinfo can't be trusted with utf-8 filenames!)
			$this->container['extension'] = ltrim(strrchr(ltrim($this->container['name'], '.'), '.'),'.');
			if (empty($this->container['extension']))
			{
				$this->container['basename'] = $this->container['name'];
			}
			else
			{
				$this->container['basename'] = substr($this->container['name'], 0, strlen($this->container['name'])-(strlen($this->container['extension'])+1));
			}

			// does this upload exceed the maximum size?
			if ( ! empty($this->config['max_size']) and is_numeric($this->config['max_size']) and $this->container['size'] > $this->config['max_size'])
			{
				$this->addError(static::UPLOAD_ERR_MAX_SIZE);
			}

			// add mimetype information
			try
			{
				$handle = finfo_open(FILEINFO_MIME_TYPE);
				$this->container['mimetype'] = finfo_file($handle, $this->container['tmp_name']);
				finfo_close($handle);
			}
			// this will only work if PHP errors are converted into ErrorException (like when you use FuelPHP)
			catch (\ErrorException $e)
			{
				$this->container['mimetype'] = false;
				$this->addError(UPLOAD_ERR_NO_FILE);
			}

			// make sure it contains something valid
			if (empty($this->container['mimetype']) or strpos($this->container['mimetype'], '/') === false)
			{
				$this->container['mimetype'] = 'application/octet-stream';
			}

			// split the mimetype info so we can run some tests
			preg_match('|^(.*)/(.*)|', $this->container['mimetype'], $mimeinfo);

			// check the file extension black- and whitelists
			if (in_array(strtolower($this->container['extension']), (array) $this->config['ext_blacklist']))
			{
				$this->addError(static::UPLOAD_ERR_EXT_BLACKLISTED);
			}
			elseif ( ! empty($this->config['ext_whitelist']) and ! in_array(strtolower($this->container['extension']), (array) $this->config['ext_whitelist']))
			{
				$this->addError(static::UPLOAD_ERR_EXT_NOT_WHITELISTED);
			}

			// check the file type black- and whitelists
			if (in_array($mimeinfo[1], (array) $this->config['type_blacklist']))
			{
				$this->addError(static::UPLOAD_ERR_TYPE_BLACKLISTED);
			}
			if ( ! empty($this->config['type_whitelist']) and ! in_array($mimeinfo[1], (array) $this->config['type_whitelist']))
			{
				$this->addError(static::UPLOAD_ERR_TYPE_NOT_WHITELISTED);
			}

			// check the file mimetype black- and whitelists
			if (in_array($this->container['mimetype'], (array) $this->config['mime_blacklist']))
			{
				$this->addError(static::UPLOAD_ERR_MIME_BLACKLISTED);
			}
			elseif ( ! empty($this->config['mime_whitelist']) and ! in_array($this->container['mimetype'], (array) $this->config['mime_whitelist']))
			{
				$this->addError(static::UPLOAD_ERR_MIME_NOT_WHITELISTED);
			}

			// validation finished, call the post-validation callback
			$this->runCallbacks('after_validation');
		}
		else
		{
			// upload was already a failure, store the corresponding error
			$this->addError($this->container['error']);
		}

		// set the flag to indicate we ran the validation
		$this->isValidated = true;

		// return the validation state
		return $this->isValid;
	}
722514
public function getValidationErrors()
    {
        if ($this->isValid()) {
            return [];
        }
        
        // if it's already cached, just return it
        if (count($this->validationErrors) > 0) {
            return $this->validationErrors;
        }


        // All errors can be spotted in the fields
        foreach ($this->getFields() as $field) {
            if (!$field->isValid()) {
                $this->validationErrors[$field->getName()] = $field->getErrors(true);
            }
        }

        return $this->validationErrors;
    }
47991
public function validates()
	{
		if ( ! isset(static::$_rules) or count(static::$_rules) < 0)
		{
			return true;
		}

		$vars = $this->_data;

		// Set default if there are any
		isset(static::$_defaults) and $vars = $vars + static::$_defaults;
		$vars = $this->pre_validate($vars);

		return $this->run_validation($vars);
	}
1188727
private function validateRecord()
    {
        // Abort if beforeValidate() fails
        if ($this->fireModelEvent('validating') === false) return false;

        $validator = Validator::make($this->getAttributes(), $this->rules, $this->messages);
        $result = $validator->passes();

        // Update errors based on result
        $this->errors = ($result) ? new MessageBag : $validator->messages();

        $this->fireModelEvent('validated', false);

        return $result;
    }
420985
public function validateModelClass()
    {
        if ($this->isReservedKeyword($this->modelClass)) {
            $this->addError('modelClass', 'Class name cannot be a reserved PHP keyword.');
        }
        if ((empty($this->indexName) || substr_compare($this->indexName, '*', -1, 1)) && $this->modelClass == '') {
            $this->addError('modelClass', 'Model Class cannot be blank if table name does not end with asterisk.');
        }
    }
513551
public function getModelStaticValidationMessages()
    {
        $model = $this->getDataModel();

        return isset($model::$messages) && is_array($model::$messages) ? $model::$messages : false;
    }
1040684
public function validate()
    {
        $this->_errors = [];
        $success = true;
        foreach ($this->fields as $name => $field) {
            /** @var $field Field */
            if (!$field->validate($this, $this->getExtraValidatorFor($name))) {
                $success = false;
            }
        }

        return $success && count($this->_errors) === 0;
    }
845559
public function validateTranslations()
    {
        $valid = !empty($this->owner->{$this->translationsAttribute});
        $activeTranslations = 0;
        foreach ($this->owner->{$this->translationsAttribute} as $model) {
            if ($this->isTranslationActive($model)) {
                $activeTranslations++;
                $valid = $valid && $model->validate();
            }
        }
        return $activeTranslations>0 && $valid;
    }
973706
public function validateModelClass()
    {
        if ($this->isReservedKeyword($this->modelClass)) {
            $this->addError('modelClass', 'Class name cannot be a reserved PHP keyword.');
        }
        if ((empty($this->tableName) || substr_compare($this->tableName, '*', -1, 1)) && $this->modelClass == '') {
            $this->addError('modelClass', 'Model Class cannot be blank if table name does not end with asterisk.');
        }
    }
1289119
public function getValidationRules()
    {
        $rules = parent::getValidationRules();

        foreach ($rules as &$rule) {
            if ($rule !== '_unique') {
                continue;
            }

            $model = $this->resolvePath();
            $table = $model->getTable();

            $rule = 'unique:'.$table.','.$this->getModelAttributeKey();
            if ($model->exists) {
                $rule .= ','.$model->getKey();
            }
        }
        unset($rule);

        return [$this->getPath() => $rules];
    }
1015991
protected function validate()
    {
        if (!$this->validator instanceof ValidatorInterface) {
            return;
        }

        $valid = true;
        if ($this->getEntityContainerMap()->count() > 0) {
            $entityContainers = $this->getEntityContainerMap()->getAll();

            $this->logger->debug('start form entity valiation', array('name' => $this->getName()));

            /**
             * @var $entityContainer    \Naucon\Form\Mapper\EntityContainerInterface
             */
            foreach ($entityContainers as $entityContainer) {
                if ($entityContainer->hasValidate()) {
                    $this->logger->debug('invoke form prevalidator hook', array('name' => $this->getName(), 'entity' => $entityContainer->getName()));
                    // prevalidation hook
                    $entityContainer->invokeHook('prevalidatorHook');

                    $violations = $this->validator->validate($entityContainer->getEntity(), null, $this->configuration->get('validation_groups'));
                    if (is_array($violations) && count($violations)) {
                        // TODO set FormValidations to $entityContainer
                        /**
                         * @var \Naucon\Form\Validator\ViolationInterface $violation
                         */
                        $violationsDump = array();
                        foreach ($violations as $violation) {
                            $violationsDump[$violation->getName()] = $violation->getMessage();
                            $entityContainer->setError($violation->getName(), new FormError($violation->getName(), $violation->getMessage()));
                        }
                        $valid = false;

                        $this->logger->debug('form entity violations', array('name' => $this->getName(), 'entity' => $entityContainer->getName(), 'violations' => $violationsDump));
                    }

                    // postvalidation hook
                    $this->logger->debug('invoke form postvalidator hook', array('name' => $this->getName(), 'entity' => $entityContainer->getName()));
                    $entityContainer->invokeHook('postvalidatorHook');

                    if ($entityContainer->hasErrors()) {
                        $valid = false;
                    }
                }
            }
        }

        if ($valid) {
            $this->logger->debug('finished form entity valiation successful', array('name' => $this->getName()));
        } else {
            $this->logger->debug('finished form entity valiation failed', array('name' => $this->getName()));
        }
        $this->setValid($valid);
    }