Yii2 Bootstrap 3
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

277 lines
10 KiB

14 years ago
<?php
/**
14 years ago
* Validator class file.
14 years ago
*
* @link http://www.yiiframework.com/
14 years ago
* @copyright Copyright &copy; 2008-2012 Yii Software LLC
14 years ago
* @license http://www.yiiframework.com/license/
*/
14 years ago
namespace yii\validators;
14 years ago
/**
14 years ago
* Validator is the base class for all validators.
14 years ago
*
14 years ago
* Child classes must override the [[validateAttribute]] method to provide the actual
* logic of performing data validation. Child classes may also override [[clientValidateAttribute]]
* to provide client-side validation support.
14 years ago
*
14 years ago
* Validator defines the following properties that are common among concrete validators:
14 years ago
*
14 years ago
* - [[attributes]]: array, list of attributes to be validated;
* - [[message]]: string, the error message used when validation fails;
* - [[on]]: string, scenarios on which the validator applies.
*
* Validator also declares a set of [[builtInValidators|built-in validators] which can
* be referenced using short names. They are listed as follows:
*
* - `required`: [[RequiredValidator]]
* - `filter`: [[FilterValidator]]
* - `match`: [[RegularExpressionValidator]]
* - `email`: [[EmailValidator]]
* - `url`: [[UrlValidator]]
* - `unique`: [[UniqueValidator]]
* - `compare`: [[CompareValidator]]
* - `in`: [[RangeValidator]]
14 years ago
* - `boolean`: [[BooleanValidator]]
* - `string`: [[StringValidator]]
* - `integer`: [[NumberValidator]]
* - `double`: [[NumberValidator]]
* - `date`: [[DateValidator]]
14 years ago
* - `file`: [[FileValidator]]
14 years ago
* - `captcha`: [[CaptchaValidator]]
14 years ago
* - `default`: [[DefaultValueValidator]]
* - `exist`: [[ExistValidator]]
* - `safe`: [[SafeValidator]]
* - `unsafe`: [[UnsafeValidator]]
14 years ago
*
* @author Qiang Xue <qiang.xue@gmail.com>
14 years ago
* @since 2.0
14 years ago
*/
14 years ago
abstract class Validator extends \yii\base\Component
14 years ago
{
/**
14 years ago
* @var array list of built-in validators (name => class or configuration)
14 years ago
*/
public static $builtInValidators = array(
14 years ago
'required' => '\yii\validators\RequiredValidator',
'match' => '\yii\validators\RegularExpressionValidator',
'email' => '\yii\validators\EmailValidator',
'url' => '\yii\validators\UrlValidator',
14 years ago
'safe' => '\yii\validators\SafeValidator',
'unsafe' => '\yii\validators\UnsafeValidator',
'filter' => '\yii\validators\FilterValidator',
14 years ago
'captcha' => '\yii\validators\CaptchaValidator',
'default' => '\yii\validators\DefaultValueValidator',
14 years ago
'in' => '\yii\validators\RangeValidator',
'boolean' => '\yii\validators\BooleanValidator',
'string' => '\yii\validators\StringValidator',
14 years ago
'integer' => '\yii\validators\IntegerValidator',
14 years ago
'double' => '\yii\validators\NumberValidator',
'compare' => '\yii\validators\CompareValidator',
'file' => '\yii\validators\FileValidator',
'date' => '\yii\validators\DateValidator',
14 years ago
'unique' => '\yii\validators\UniqueValidator',
'exist' => '\yii\validators\ExistValidator',
14 years ago
);
/**
* @var array list of attributes to be validated.
*/
public $attributes;
/**
14 years ago
* @var string the user-defined error message. Error message may contain some placeholders
* that will be replaced with the actual values by the validator.
* The `{attribute}` and `{value}` are placeholders supported by all validators.
* They will be replaced with the attribute label and value, respectively.
14 years ago
*/
public $message;
/**
* @var array list of scenarios that the validator should be applied.
* Each array value refers to a scenario name with the same name as its array key.
*/
public $on;
/**
* @var array list of scenarios that the validator should not be applied to.
* Each array value refers to a scenario name with the same name as its array key.
*/
public $except;
/**
14 years ago
* @var boolean whether this validation rule should be skipped if the attribute being validated
14 years ago
* already has some validation error according to the previous rules. Defaults to true.
14 years ago
*/
14 years ago
public $skipOnError = true;
14 years ago
/**
* @var boolean whether attributes listed with this validator should be considered safe for
* massive assignment. Defaults to true.
14 years ago
*/
public $safe = true;
/**
14 years ago
* @var boolean whether to enable client-side validation. Defaults to true.
* Please refer to [[\yii\web\ActiveForm::enableClientValidation]] for more details about
* client-side validation.
14 years ago
*/
public $enableClientValidation = true;
/**
* Validates a single attribute.
14 years ago
* Child classes must implement this method to provide the actual validation logic.
14 years ago
* @param \yii\base\Model $object the data object being validated
14 years ago
* @param string $attribute the name of the attribute to be validated.
*/
14 years ago
abstract public function validateAttribute($object, $attribute);
14 years ago
/**
* Creates a validator object.
14 years ago
* @param string $type the validator type. This can be a method name,
* a built-in validator name, a class name, or a path alias of validator class.
* @param \yii\base\Model $object the data object being validated.
14 years ago
* @param mixed $attributes list of attributes to be validated. This can be either an array of
* the attribute names or a string of comma-separated attribute names.
* @param array $params initial values to be applied to the validator properties
14 years ago
* @return Validator the validator
14 years ago
*/
14 years ago
public static function createValidator($type, $object, $attributes, $params = array())
14 years ago
{
14 years ago
if (!is_array($attributes)) {
14 years ago
$attributes = preg_split('/[\s,]+/', $attributes, -1, PREG_SPLIT_NO_EMPTY);
14 years ago
}
14 years ago
14 years ago
if (isset($params['on'])) {
if (is_array($params['on'])) {
14 years ago
$on = $params['on'];
13 years ago
} else {
14 years ago
$on = preg_split('/[\s,]+/', $params['on'], -1, PREG_SPLIT_NO_EMPTY);
14 years ago
}
$params['on'] = empty($on) ? array() : array_combine($on, $on);
13 years ago
} else {
14 years ago
$params['on'] = array();
14 years ago
}
if (isset($params['except'])) {
if (is_array($params['except'])) {
$except = $params['except'];
} else {
$except = preg_split('/[\s,]+/', $params['except'], -1, PREG_SPLIT_NO_EMPTY);
}
$params['except'] = empty($on) ? array() : array_combine($except, $except);
} else {
$params['except'] = array();
}
13 years ago
if (method_exists($object, $type)) {
// method-based validator
14 years ago
$config = array(
'class' => '\yii\validators\InlineValidator',
'method' => $type,
'attributes' => $attributes,
);
13 years ago
} else {
14 years ago
if (is_string($type) && isset(self::$builtInValidators[$type])) {
$type = self::$builtInValidators[$type];
}
$config = array(
'class' => $type,
'attributes' => $attributes,
);
}
foreach ($params as $name => $value) {
14 years ago
$config[$name] = $value;
14 years ago
}
13 years ago
$validator = \Yii::createObject($config);
14 years ago
return $validator;
}
/**
* Validates the specified object.
14 years ago
* @param \yii\base\Model $object the data object being validated
14 years ago
* @param array $attributes the list of attributes to be validated. Defaults to null,
14 years ago
* meaning every attribute listed in [[attributes]] will be validated.
14 years ago
*/
public function validate($object, $attributes = null)
{
14 years ago
if (is_array($attributes)) {
14 years ago
$attributes = array_intersect($this->attributes, $attributes);
13 years ago
} else {
14 years ago
$attributes = $this->attributes;
14 years ago
}
foreach ($attributes as $attribute) {
if (!$this->skipOnError || !$object->hasErrors($attribute)) {
14 years ago
$this->validateAttribute($object, $attribute);
14 years ago
}
14 years ago
}
}
/**
* Returns the JavaScript needed for performing client-side validation.
14 years ago
*
* You may override this method to return the JavaScript validation code if
* the validator can support client-side validation.
*
* The following JavaScript variables are predefined and can be used in the validation code:
*
* - `attribute`: the name of the attribute being validated.
* - `value`: the value being validated.
* - `messages`: an array used to hold the validation error messages for the attribute.
*
* @param \yii\base\Model $object the data object being validated
14 years ago
* @param string $attribute the name of the attribute to be validated.
14 years ago
* @return string the client-side validation script. Null if the validator does not support
* client-side validation.
* @see enableClientValidation
* @see \yii\web\ActiveForm::enableClientValidation
14 years ago
*/
public function clientValidateAttribute($object, $attribute)
{
}
/**
* Returns a value indicating whether the validator applies to the specified scenario.
* A validator applies to a scenario as long as any of the following conditions is met:
14 years ago
*
* - the validator's `on` property is empty
* - the validator's `on` property contains the specified scenario
*
14 years ago
* @param string $scenario scenario name
13 years ago
* @param string|null $attribute the attribute name to check. If this is not null,
* the method will also check if the attribute appears in [[attributes]].
14 years ago
* @return boolean whether the validator applies to the specified scenario.
*/
13 years ago
public function applyTo($scenario, $attribute = null)
14 years ago
{
$applies = !isset($this->except[$scenario]) && (empty($this->on) || isset($this->on[$scenario]));
return $attribute === null ? $applies : $applies && in_array($attribute, $this->attributes, true);
14 years ago
}
/**
14 years ago
* Adds an error about the specified attribute to the model object.
14 years ago
* This is a helper method that performs message selection and internationalization.
14 years ago
* @param \yii\base\Model $object the data object being validated
14 years ago
* @param string $attribute the attribute being validated
* @param string $message the error message
* @param array $params values for the placeholders in the error message
*/
14 years ago
public function addError($object, $attribute, $message, $params = array())
14 years ago
{
$params['{attribute}'] = $object->getAttributeLabel($attribute);
14 years ago
$params['{value}'] = $object->$attribute;
14 years ago
$object->addError($attribute, strtr($message, $params));
}
/**
* Checks if the given value is empty.
* A value is considered empty if it is null, an empty array, or the trimmed result is an empty string.
* Note that this method is different from PHP empty(). It will return false when the value is 0.
* @param mixed $value the value to be checked
* @param boolean $trim whether to perform trimming before checking if the string is empty. Defaults to false.
* @return boolean whether the value is empty
*/
14 years ago
public function isEmpty($value, $trim = false)
14 years ago
{
14 years ago
return $value === null || $value === array() || $value === ''
|| $trim && is_scalar($value) && trim($value) === '';
14 years ago
}
}