Validator.php 9.73 KB
Newer Older
w  
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
w  
Qiang Xue committed
5 6 7
 * @license http://www.yiiframework.com/license/
 */

w  
Qiang Xue committed
8 9
namespace yii\validators;

Qiang Xue committed
10
use Yii;
Qiang Xue committed
11
use yii\base\Component;
Qiang Xue committed
12
use yii\base\NotSupportedException;
Qiang Xue committed
13

w  
Qiang Xue committed
14
/**
w  
Qiang Xue committed
15
 * Validator is the base class for all validators.
w  
Qiang Xue committed
16
 *
Qiang Xue committed
17 18
 * Child classes should override the [[validateAttribute()]] method to provide the actual
 * logic of performing data validation. Child classes may also override [[clientValidateAttribute()]]
w  
Qiang Xue committed
19
 * to provide client-side validation support.
w  
Qiang Xue committed
20
 *
Qiang Xue committed
21
 * Validator declares a set of [[builtInValidators|built-in validators] which can
w  
Qiang Xue committed
22 23
 * be referenced using short names. They are listed as follows:
 *
w  
Qiang Xue committed
24 25
 * - `boolean`: [[BooleanValidator]]
 * - `captcha`: [[CaptchaValidator]]
Qiang Xue committed
26 27
 * - `compare`: [[CompareValidator]]
 * - `date`: [[DateValidator]]
w  
Qiang Xue committed
28
 * - `default`: [[DefaultValueValidator]]
Qiang Xue committed
29 30
 * - `double`: [[NumberValidator]]
 * - `email`: [[EmailValidator]]
w  
Qiang Xue committed
31
 * - `exist`: [[ExistValidator]]
Qiang Xue committed
32 33 34 35 36 37 38 39 40
 * - `file`: [[FileValidator]]
 * - `filter`: [[FilterValidator]]
 * - `in`: [[RangeValidator]]
 * - `integer`: [[NumberValidator]]
 * - `match`: [[RegularExpressionValidator]]
 * - `required`: [[RequiredValidator]]
 * - `string`: [[StringValidator]]
 * - `unique`: [[UniqueValidator]]
 * - `url`: [[UrlValidator]]
w  
Qiang Xue committed
41 42
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
w  
Qiang Xue committed
43
 * @since 2.0
w  
Qiang Xue committed
44
 */
Qiang Xue committed
45
abstract class Validator extends Component
w  
Qiang Xue committed
46 47
{
	/**
w  
Qiang Xue committed
48
	 * @var array list of built-in validators (name => class or configuration)
w  
Qiang Xue committed
49 50
	 */
	public static $builtInValidators = array(
Qiang Xue committed
51
		'boolean' => 'yii\validators\BooleanValidator',
Qiang Xue committed
52
		'captcha' => 'yii\captcha\CaptchaValidator',
Qiang Xue committed
53 54 55 56 57 58 59 60 61
		'compare' => 'yii\validators\CompareValidator',
		'date' => 'yii\validators\DateValidator',
		'default' => 'yii\validators\DefaultValueValidator',
		'double' => 'yii\validators\NumberValidator',
		'email' => 'yii\validators\EmailValidator',
		'exist' => 'yii\validators\ExistValidator',
		'file' => 'yii\validators\FileValidator',
		'filter' => 'yii\validators\FilterValidator',
		'in' => 'yii\validators\RangeValidator',
Qiang Xue committed
62 63 64 65
		'integer' => array(
			'class' => 'yii\validators\NumberValidator',
			'integerOnly' => true,
		),
Qiang Xue committed
66
		'match' => 'yii\validators\RegularExpressionValidator',
Qiang Xue committed
67
		'number' => 'yii\validators\NumberValidator',
Qiang Xue committed
68 69 70 71
		'required' => 'yii\validators\RequiredValidator',
		'string' => 'yii\validators\StringValidator',
		'unique' => 'yii\validators\UniqueValidator',
		'url' => 'yii\validators\UrlValidator',
w  
Qiang Xue committed
72 73 74 75 76
	);

	/**
	 * @var array list of attributes to be validated.
	 */
77
	public $attributes = array();
w  
Qiang Xue committed
78
	/**
79 80 81 82 83
	 * @var string the user-defined error message. It may contain the following placeholders which
	 * will be replaced accordingly by the validator:
	 *
	 * - `{attribute}`: the label of the attribute being validated
	 * - `{value}`: the value of the attribute being validated
w  
Qiang Xue committed
84 85 86
	 */
	public $message;
	/**
Qiang Xue committed
87
	 * @var array list of scenarios that the validator can be applied to.
w  
Qiang Xue committed
88
	 */
Qiang Xue committed
89
	public $on = array();
Qiang Xue committed
90 91 92
	/**
	 * @var array list of scenarios that the validator should not be applied to.
	 */
Qiang Xue committed
93
	public $except = array();
w  
Qiang Xue committed
94
	/**
w  
Qiang Xue committed
95
	 * @var boolean whether this validation rule should be skipped if the attribute being validated
Qiang Xue committed
96
	 * already has some validation error according to some previous rules. Defaults to true.
w  
Qiang Xue committed
97
	 */
w  
Qiang Xue committed
98
	public $skipOnError = true;
Qiang Xue committed
99 100 101 102 103
	/**
	 * @var boolean whether this validation rule should be skipped if the attribute value
	 * is null or an empty string.
	 */
	public $skipOnEmpty = true;
Qiang Xue committed
104 105 106 107 108 109 110
	/**
	 * @var boolean whether to enable client-side validation for this validator.
	 * The actual client-side validation is done via the JavaScript code returned
	 * by [[clientValidateAttribute()]]. If that method returns null, even if this property
	 * is true, no client-side validation will be done by this validator.
	 */
	public $enableClientValidation = true;
Qiang Xue committed
111

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

	/**
	 * Creates a validator object.
w  
Qiang Xue committed
122
	 * @param string $type the validator type. This can be a method name,
Qiang Xue committed
123 124 125
	 * a built-in validator name, a class name, or a path alias of the validator class.
	 * @param \yii\base\Model $object the data object to be validated.
	 * @param array|string $attributes list of attributes to be validated. This can be either an array of
w  
Qiang Xue committed
126 127
	 * 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
128
	 * @return Validator the validator
w  
Qiang Xue committed
129
	 */
w  
Qiang Xue committed
130
	public static function createValidator($type, $object, $attributes, $params = array())
w  
Qiang Xue committed
131
	{
w  
Qiang Xue committed
132
		if (!is_array($attributes)) {
w  
Qiang Xue committed
133
			$attributes = preg_split('/[\s,]+/', $attributes, -1, PREG_SPLIT_NO_EMPTY);
w  
Qiang Xue committed
134
		}
Qiang Xue committed
135
		$params['attributes'] = $attributes;
w  
Qiang Xue committed
136

Qiang Xue committed
137 138
		if (isset($params['on']) && !is_array($params['on'])) {
			$params['on'] = preg_split('/[\s,]+/', $params['on'], -1, PREG_SPLIT_NO_EMPTY);
w  
Qiang Xue committed
139 140
		}

Qiang Xue committed
141 142
		if (isset($params['except']) && !is_array($params['except'])) {
			$params['except'] = preg_split('/[\s,]+/', $params['except'], -1, PREG_SPLIT_NO_EMPTY);
Qiang Xue committed
143 144
		}

Alexander Makarov committed
145 146
		if (method_exists($object, $type)) {
			// method-based validator
Qiang Xue committed
147 148
			$params['class'] = __NAMESPACE__ . '\InlineValidator';
			$params['method'] = $type;
Qiang Xue committed
149
		} else {
150 151
			if (isset(static::$builtInValidators[$type])) {
				$type = static::$builtInValidators[$type];
w  
Qiang Xue committed
152
			}
Qiang Xue committed
153 154 155 156 157 158 159
			if (is_array($type)) {
				foreach ($type as $name => $value) {
					$params[$name] = $value;
				}
			} else {
				$params['class'] = $type;
			}
w  
Qiang Xue committed
160 161
		}

Qiang Xue committed
162
		return Yii::createObject($params);
w  
Qiang Xue committed
163 164 165 166
	}

	/**
	 * Validates the specified object.
w  
Qiang Xue committed
167
	 * @param \yii\base\Model $object the data object being validated
168 169 170 171
	 * @param array|null $attributes the list of attributes to be validated.
	 * Note that if an attribute is not associated with the validator,
	 * it will be ignored.
	 * If this parameter is null, every attribute listed in [[attributes]] will be validated.
w  
Qiang Xue committed
172 173 174
	 */
	public function validate($object, $attributes = null)
	{
w  
Qiang Xue committed
175
		if (is_array($attributes)) {
w  
Qiang Xue committed
176
			$attributes = array_intersect($this->attributes, $attributes);
Qiang Xue committed
177
		} else {
w  
Qiang Xue committed
178
			$attributes = $this->attributes;
w  
Qiang Xue committed
179 180
		}
		foreach ($attributes as $attribute) {
Qiang Xue committed
181
			$skip = $this->skipOnError && $object->hasErrors($attribute)
resurtm committed
182
				|| $this->skipOnEmpty && $this->isEmpty($object->$attribute);
Qiang Xue committed
183
			if (!$skip) {
w  
Qiang Xue committed
184
				$this->validateAttribute($object, $attribute);
w  
Qiang Xue committed
185
			}
w  
Qiang Xue committed
186 187 188
		}
	}

Qiang Xue committed
189 190 191 192 193 194
	/**
	 * Validates a value.
	 * A validator class can implement this method to support data validation out of the context of a data model.
	 * @param mixed $value the data value to be validated.
	 * @throws NotSupportedException if data validation without a model is not supported
	 */
Qiang Xue committed
195 196
	public function validateValue($value)
	{
197
		throw new NotSupportedException(get_class($this) . ' does not support validateValue().');
Qiang Xue committed
198 199
	}

w  
Qiang Xue committed
200 201
	/**
	 * Returns the JavaScript needed for performing client-side validation.
w  
Qiang Xue committed
202 203 204 205 206 207 208 209 210 211 212
	 *
	 * 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
213
	 * @param string $attribute the name of the attribute to be validated.
214 215
	 * @param \yii\base\View $view the view object that is going to be used to render views or view files
	 * containing a model form with this validator applied.
w  
Qiang Xue committed
216 217 218
	 * @return string the client-side validation script. Null if the validator does not support
	 * client-side validation.
	 * @see \yii\web\ActiveForm::enableClientValidation
w  
Qiang Xue committed
219
	 */
220
	public function clientValidateAttribute($object, $attribute, $view)
w  
Qiang Xue committed
221
	{
Qiang Xue committed
222
		return null;
w  
Qiang Xue committed
223 224 225
	}

	/**
226 227 228
	 * Returns a value indicating whether the validator is active for the given scenario and attribute.
	 *
	 * A validator is active if
w  
Qiang Xue committed
229
	 *
230
	 * - the validator's `on` property is empty, or
w  
Qiang Xue committed
231 232
	 * - the validator's `on` property contains the specified scenario
	 *
w  
Qiang Xue committed
233 234 235
	 * @param string $scenario scenario name
	 * @return boolean whether the validator applies to the specified scenario.
	 */
Qiang Xue committed
236
	public function isActive($scenario)
w  
Qiang Xue committed
237
	{
Qiang Xue committed
238
		return !in_array($scenario, $this->except, true) && (empty($this->on) || in_array($scenario, $this->on, true));
w  
Qiang Xue committed
239 240 241
	}

	/**
w  
Qiang Xue committed
242
	 * Adds an error about the specified attribute to the model object.
w  
Qiang Xue committed
243
	 * This is a helper method that performs message selection and internationalization.
w  
Qiang Xue committed
244
	 * @param \yii\base\Model $object the data object being validated
w  
Qiang Xue committed
245 246 247 248
	 * @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
249
	public function addError($object, $attribute, $message, $params = array())
w  
Qiang Xue committed
250
	{
Qiang Xue committed
251
		$value = $object->$attribute;
w  
Qiang Xue committed
252
		$params['{attribute}'] = $object->getAttributeLabel($attribute);
Qiang Xue committed
253
		$params['{value}'] = is_array($value) ? 'array()' : $value;
w  
Qiang Xue committed
254 255 256 257 258 259 260 261 262 263 264
		$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
265
	public function isEmpty($value, $trim = false)
w  
Qiang Xue committed
266
	{
w  
Qiang Xue committed
267
		return $value === null || $value === array() || $value === ''
Qiang Xue committed
268
			|| $trim && is_scalar($value) && trim($value) === '';
w  
Qiang Xue committed
269 270
	}
}