Validator.php 9.18 KB
Newer Older
w  
Qiang Xue committed
1 2
<?php
/**
w  
Qiang Xue committed
3
 * Validator class file.
w  
Qiang Xue committed
4 5
 *
 * @link http://www.yiiframework.com/
w  
Qiang Xue committed
6
 * @copyright Copyright &copy; 2008-2012 Yii Software LLC
w  
Qiang Xue committed
7 8 9
 * @license http://www.yiiframework.com/license/
 */

w  
Qiang Xue committed
10 11
namespace yii\validators;

w  
Qiang Xue committed
12
/**
w  
Qiang Xue committed
13
 * Validator is the base class for all validators.
w  
Qiang Xue committed
14
 *
w  
Qiang Xue committed
15 16 17
 * 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.
w  
Qiang Xue committed
18
 *
w  
Qiang Xue committed
19
 * Validator defines the following properties that are common among concrete validators:
w  
Qiang Xue committed
20
 *
w  
Qiang Xue committed
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
 * - [[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]]
w  
Qiang Xue committed
36 37 38 39 40
 * - `boolean`: [[BooleanValidator]]
 * - `string`: [[StringValidator]]
 * - `integer`: [[NumberValidator]]
 * - `double`: [[NumberValidator]]
 * - `date`: [[DateValidator]]
w  
Qiang Xue committed
41
 * - `file`: [[FileValidator]]
w  
Qiang Xue committed
42
 * - `captcha`: [[CaptchaValidator]]
w  
Qiang Xue committed
43 44 45 46
 * - `default`: [[DefaultValueValidator]]
 * - `exist`: [[ExistValidator]]
 * - `safe`: [[SafeValidator]]
 * - `unsafe`: [[UnsafeValidator]]
w  
Qiang Xue committed
47 48
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
w  
Qiang Xue committed
49
 * @since 2.0
w  
Qiang Xue committed
50
 */
w  
Qiang Xue committed
51
abstract class Validator extends \yii\base\Component
w  
Qiang Xue committed
52 53
{
	/**
w  
Qiang Xue committed
54
	 * @var array list of built-in validators (name => class or configuration)
w  
Qiang Xue committed
55 56
	 */
	public static $builtInValidators = array(
w  
Qiang Xue committed
57 58 59 60
		'required' => '\yii\validators\RequiredValidator',
		'match' => '\yii\validators\RegularExpressionValidator',
		'email' => '\yii\validators\EmailValidator',
		'url' => '\yii\validators\UrlValidator',
w  
Qiang Xue committed
61 62 63
		'safe' => '\yii\validators\SafeValidator',
		'unsafe' => '\yii\validators\UnsafeValidator',
		'filter' => '\yii\validators\FilterValidator',
w  
Qiang Xue committed
64 65
		'captcha' => '\yii\validators\CaptchaValidator',
		'default' => '\yii\validators\DefaultValueValidator',
w  
Qiang Xue committed
66 67 68
		'in' => '\yii\validators\RangeValidator',
		'boolean' => '\yii\validators\BooleanValidator',
		'string' => '\yii\validators\StringValidator',
w  
Qiang Xue committed
69
		'integer' => '\yii\validators\IntegerValidator',
w  
Qiang Xue committed
70 71 72 73 74
		'double' => '\yii\validators\NumberValidator',
		'compare' => '\yii\validators\CompareValidator',

		'file' => '\yii\validators\FileValidator',
		'date' => '\yii\validators\DateValidator',
w  
Qiang Xue committed
75 76 77
		'unique' => '\yii\validators\UniqueValidator',
		'exist' => '\yii\validators\ExistValidator',

w  
Qiang Xue committed
78 79 80 81 82 83 84
	);

	/**
	 * @var array list of attributes to be validated.
	 */
	public $attributes;
	/**
w  
Qiang Xue committed
85 86 87 88
	 * @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.
w  
Qiang Xue committed
89 90 91 92 93 94 95 96
	 */
	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;
	/**
w  
Qiang Xue committed
97
	 * @var boolean whether this validation rule should be skipped if the attribute being validated
w  
Qiang Xue committed
98
	 * already has some validation error according to the previous rules. Defaults to true.
w  
Qiang Xue committed
99
	 */
w  
Qiang Xue committed
100
	public $skipOnError = true;
w  
Qiang Xue committed
101 102 103
	/**
	 * @var boolean whether attributes listed with this validator should be considered safe for
	 * massive assignment. Defaults to true.
w  
Qiang Xue committed
104 105 106
	 */
	public $safe = true;
	/**
w  
Qiang Xue committed
107 108 109
	 * @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.
w  
Qiang Xue committed
110 111 112 113 114
	 */
	public $enableClientValidation = true;

	/**
	 * Validates a single attribute.
w  
Qiang Xue committed
115
	 * Child classes must implement this method to provide the actual validation logic.
w  
Qiang Xue committed
116
	 * @param \yii\base\Model $object the data object being validated
w  
Qiang Xue committed
117 118
	 * @param string $attribute the name of the attribute to be validated.
	 */
w  
Qiang Xue committed
119
	abstract public function validateAttribute($object, $attribute);
w  
Qiang Xue committed
120 121 122

	/**
	 * Creates a validator object.
w  
Qiang Xue committed
123 124 125
	 * @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.
w  
Qiang Xue committed
126 127 128
	 * @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
w  
Qiang Xue committed
129
	 * @return Validator the validator
w  
Qiang Xue committed
130
	 */
w  
Qiang Xue committed
131
	public static function createValidator($type, $object, $attributes, $params = array())
w  
Qiang Xue committed
132
	{
w  
Qiang Xue committed
133
		if (!is_array($attributes)) {
w  
Qiang Xue committed
134
			$attributes = preg_split('/[\s,]+/', $attributes, -1, PREG_SPLIT_NO_EMPTY);
w  
Qiang Xue committed
135
		}
w  
Qiang Xue committed
136

w  
Qiang Xue committed
137 138
		if (isset($params['on'])) {
			if (is_array($params['on'])) {
w  
Qiang Xue committed
139
				$on = $params['on'];
w  
Qiang Xue committed
140 141
			}
			else {
w  
Qiang Xue committed
142
				$on = preg_split('/[\s,]+/', $params['on'], -1, PREG_SPLIT_NO_EMPTY);
w  
Qiang Xue committed
143 144 145 146 147
			}
			$params['on'] = empty($on) ? array() : array_combine($on, $on);
		}
		else {
			$params['on'] = array();
w  
Qiang Xue committed
148 149
		}

w  
Qiang Xue committed
150 151 152 153 154 155
		if (method_exists($object, $type)) {  // method-based validator
			$config = array(
				'class'	=> '\yii\validators\InlineValidator',
				'method' => $type,
				'attributes' => $attributes,
			);
w  
Qiang Xue committed
156
		}
w  
Qiang Xue committed
157 158 159 160 161 162 163 164 165 166
		else {
			if (is_string($type) && isset(self::$builtInValidators[$type])) {
				$type = self::$builtInValidators[$type];
			}
			$config = array(
				'class'	=> $type,
				'attributes' => $attributes,
			);
		}
		foreach ($params as $name => $value) {
w  
Qiang Xue committed
167
			$config[$name] = $value;
w  
Qiang Xue committed
168
		}
169
		$validator = \Yii::create($config);
w  
Qiang Xue committed
170 171 172 173 174 175

		return $validator;
	}

	/**
	 * Validates the specified object.
w  
Qiang Xue committed
176
	 * @param \yii\base\Model $object the data object being validated
w  
Qiang Xue committed
177
	 * @param array $attributes the list of attributes to be validated. Defaults to null,
w  
Qiang Xue committed
178
	 * meaning every attribute listed in [[attributes]] will be validated.
w  
Qiang Xue committed
179 180 181
	 */
	public function validate($object, $attributes = null)
	{
w  
Qiang Xue committed
182
		if (is_array($attributes)) {
w  
Qiang Xue committed
183
			$attributes = array_intersect($this->attributes, $attributes);
w  
Qiang Xue committed
184 185
		}
		else {
w  
Qiang Xue committed
186
			$attributes = $this->attributes;
w  
Qiang Xue committed
187 188 189
		}
		foreach ($attributes as $attribute) {
			if (!$this->skipOnError || !$object->hasErrors($attribute)) {
w  
Qiang Xue committed
190
				$this->validateAttribute($object, $attribute);
w  
Qiang Xue committed
191
			}
w  
Qiang Xue committed
192 193 194 195 196
		}
	}

	/**
	 * Returns the JavaScript needed for performing client-side validation.
w  
Qiang Xue committed
197 198 199 200 201 202 203 204 205 206 207
	 *
	 * 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
w  
Qiang Xue committed
208
	 * @param string $attribute the name of the attribute to be validated.
w  
Qiang Xue committed
209 210 211 212
	 * @return string the client-side validation script. Null if the validator does not support
	 * client-side validation.
	 * @see enableClientValidation
	 * @see \yii\web\ActiveForm::enableClientValidation
w  
Qiang Xue committed
213 214 215 216 217 218 219 220
	 */
	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:
w  
Qiang Xue committed
221 222 223 224
	 *
	 * - the validator's `on` property is empty
	 * - the validator's `on` property contains the specified scenario
	 *
w  
Qiang Xue committed
225 226 227 228 229 230 231 232 233
	 * @param string $scenario scenario name
	 * @return boolean whether the validator applies to the specified scenario.
	 */
	public function applyTo($scenario)
	{
		return empty($this->on) || isset($this->on[$scenario]);
	}

	/**
w  
Qiang Xue committed
234
	 * Adds an error about the specified attribute to the model object.
w  
Qiang Xue committed
235
	 * This is a helper method that performs message selection and internationalization.
w  
Qiang Xue committed
236
	 * @param \yii\base\Model $object the data object being validated
w  
Qiang Xue committed
237 238 239 240
	 * @param string $attribute the attribute being validated
	 * @param string $message the error message
	 * @param array $params values for the placeholders in the error message
	 */
w  
Qiang Xue committed
241
	public function addError($object, $attribute, $message, $params = array())
w  
Qiang Xue committed
242 243
	{
		$params['{attribute}'] = $object->getAttributeLabel($attribute);
w  
Qiang Xue committed
244
		$params['{value}'] = $object->$attribute;
w  
Qiang Xue committed
245 246 247 248 249 250 251 252 253 254 255
		$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
	 */
w  
Qiang Xue committed
256
	public function isEmpty($value, $trim = false)
w  
Qiang Xue committed
257
	{
w  
Qiang Xue committed
258 259
		return $value === null || $value === array() || $value === ''
				|| $trim && is_scalar($value) && trim($value) === '';
w  
Qiang Xue committed
260 261
	}
}