Validator.php 10 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
 * - `file`: [[FileValidator]]
 * - `filter`: [[FilterValidator]]
Gudz Taras committed
34
 * - `image`: [[ImageValidator]]
Qiang Xue committed
35 36 37 38
 * - `in`: [[RangeValidator]]
 * - `integer`: [[NumberValidator]]
 * - `match`: [[RegularExpressionValidator]]
 * - `required`: [[RequiredValidator]]
Qiang Xue committed
39
 * - `safe`: [[SafeValidator]]
Qiang Xue committed
40 41 42
 * - `string`: [[StringValidator]]
 * - `unique`: [[UniqueValidator]]
 * - `url`: [[UrlValidator]]
w  
Qiang Xue committed
43 44
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
w  
Qiang Xue committed
45
 * @since 2.0
w  
Qiang Xue committed
46
 */
Qiang Xue committed
47
abstract class Validator extends Component
w  
Qiang Xue committed
48 49
{
	/**
w  
Qiang Xue committed
50
	 * @var array list of built-in validators (name => class or configuration)
w  
Qiang Xue committed
51
	 */
Alexander Makarov committed
52
	public static $builtInValidators = [
Qiang Xue committed
53
		'boolean' => 'yii\validators\BooleanValidator',
Qiang Xue committed
54
		'captcha' => 'yii\captcha\CaptchaValidator',
Qiang Xue committed
55 56 57 58 59 60 61 62
		'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',
Gudz Taras committed
63
		'image' => 'yii\validators\ImageValidator',
Qiang Xue committed
64
		'in' => 'yii\validators\RangeValidator',
Alexander Makarov committed
65
		'integer' => [
Qiang Xue committed
66 67
			'class' => 'yii\validators\NumberValidator',
			'integerOnly' => true,
Alexander Makarov committed
68
		],
Qiang Xue committed
69
		'match' => 'yii\validators\RegularExpressionValidator',
Qiang Xue committed
70
		'number' => 'yii\validators\NumberValidator',
Qiang Xue committed
71
		'required' => 'yii\validators\RequiredValidator',
Qiang Xue committed
72
		'safe' => 'yii\validators\SafeValidator',
Qiang Xue committed
73 74 75
		'string' => 'yii\validators\StringValidator',
		'unique' => 'yii\validators\UniqueValidator',
		'url' => 'yii\validators\UrlValidator',
Alexander Makarov committed
76
	];
w  
Qiang Xue committed
77 78

	/**
79 80
	 * @var array|string attributes to be validated by this validator. For multiple attributes,
	 * please specify them as an array; for single attribute, you may use either a string or an array.
w  
Qiang Xue committed
81
	 */
Alexander Makarov committed
82
	public $attributes = [];
w  
Qiang Xue committed
83
	/**
84 85 86 87 88
	 * @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
89 90 91
	 */
	public $message;
	/**
92 93
	 * @var array|string scenarios that the validator can be applied to. For multiple scenarios,
	 * please specify them as an array; for single scenario, you may use either a string or an array.
w  
Qiang Xue committed
94
	 */
Alexander Makarov committed
95
	public $on = [];
Qiang Xue committed
96
	/**
97 98
	 * @var array|string scenarios that the validator should not be applied to. For multiple scenarios,
	 * please specify them as an array; for single scenario, you may use either a string or an array.
Qiang Xue committed
99
	 */
Alexander Makarov committed
100
	public $except = [];
w  
Qiang Xue committed
101
	/**
w  
Qiang Xue committed
102
	 * @var boolean whether this validation rule should be skipped if the attribute being validated
Qiang Xue committed
103
	 * already has some validation error according to some previous rules. Defaults to true.
w  
Qiang Xue committed
104
	 */
w  
Qiang Xue committed
105
	public $skipOnError = true;
Qiang Xue committed
106 107 108 109 110
	/**
	 * @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
111 112 113 114 115 116 117
	/**
	 * @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
118

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

	/**
	 * Creates a validator object.
w  
Qiang Xue committed
129
	 * @param string $type the validator type. This can be a method name,
Qiang Xue committed
130 131 132
	 * 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
133 134
	 * 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
135
	 * @return Validator the validator
w  
Qiang Xue committed
136
	 */
137
	public static function createValidator($type, $object, $attributes, $params = [])
w  
Qiang Xue committed
138
	{
slavcodev committed
139
		$params['attributes'] = $attributes;
Qiang Xue committed
140

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

Qiang Xue committed
158
		return Yii::createObject($params);
w  
Qiang Xue committed
159 160
	}

161 162 163 164 165 166
	/**
	 * @inheritdoc
	 */
	public function init()
	{
		parent::init();
167 168 169
		$this->attributes = (array)$this->attributes;
		$this->on = (array)$this->on;
		$this->except = (array)$this->except;
170 171
	}

w  
Qiang Xue committed
172 173
	/**
	 * Validates the specified object.
w  
Qiang Xue committed
174
	 * @param \yii\base\Model $object the data object being validated
175 176 177 178
	 * @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
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);
Qiang Xue committed
184
		} else {
w  
Qiang Xue committed
185
			$attributes = $this->attributes;
w  
Qiang Xue committed
186 187
		}
		foreach ($attributes as $attribute) {
Qiang Xue committed
188
			$skip = $this->skipOnError && $object->hasErrors($attribute)
resurtm committed
189
				|| $this->skipOnEmpty && $this->isEmpty($object->$attribute);
Qiang Xue committed
190
			if (!$skip) {
w  
Qiang Xue committed
191
				$this->validateAttribute($object, $attribute);
w  
Qiang Xue committed
192
			}
w  
Qiang Xue committed
193 194 195
		}
	}

Qiang Xue committed
196 197 198 199 200 201
	/**
	 * 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
202 203
	public function validateValue($value)
	{
204
		throw new NotSupportedException(get_class($this) . ' does not support validateValue().');
Qiang Xue committed
205 206
	}

w  
Qiang Xue committed
207 208
	/**
	 * Returns the JavaScript needed for performing client-side validation.
w  
Qiang Xue committed
209 210 211 212 213 214 215 216 217 218 219
	 *
	 * 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
220
	 * @param string $attribute the name of the attribute to be validated.
Alexander Makarov committed
221
	 * @param \yii\web\View $view the view object that is going to be used to render views or view files
222
	 * containing a model form with this validator applied.
w  
Qiang Xue committed
223 224 225
	 * @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
226
	 */
227
	public function clientValidateAttribute($object, $attribute, $view)
w  
Qiang Xue committed
228
	{
Qiang Xue committed
229
		return null;
w  
Qiang Xue committed
230 231 232
	}

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

	/**
w  
Qiang Xue committed
249
	 * Adds an error about the specified attribute to the model object.
w  
Qiang Xue committed
250
	 * This is a helper method that performs message selection and internationalization.
w  
Qiang Xue committed
251
	 * @param \yii\base\Model $object the data object being validated
w  
Qiang Xue committed
252 253 254 255
	 * @param string $attribute the attribute being validated
	 * @param string $message the error message
	 * @param array $params values for the placeholders in the error message
	 */
Alexander Makarov committed
256
	public function addError($object, $attribute, $message, $params = [])
w  
Qiang Xue committed
257
	{
Qiang Xue committed
258
		$value = $object->$attribute;
259 260 261
		$params['attribute'] = $object->getAttributeLabel($attribute);
		$params['value'] = is_array($value) ? 'array()' : $value;
		$object->addError($attribute, Yii::$app->getI18n()->format($message, $params, Yii::$app->language));
w  
Qiang Xue committed
262 263 264 265 266 267 268 269 270 271
	}

	/**
	 * 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
272
	public function isEmpty($value, $trim = false)
w  
Qiang Xue committed
273
	{
Alexander Makarov committed
274
		return $value === null || $value === [] || $value === ''
Qiang Xue committed
275
			|| $trim && is_scalar($value) && trim($value) === '';
w  
Qiang Xue committed
276 277
	}
}