Validator.php 8.78 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/
Qiang Xue committed
6
 * @copyright Copyright &copy; 2008 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;

Qiang Xue committed
12 13
use yii\base\Component;

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 52 53 54 55 56 57 58 59 60 61
		'boolean' => 'yii\validators\BooleanValidator',
		'captcha' => 'yii\validators\CaptchaValidator',
		'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 77 78
	);

	/**
	 * @var array list of attributes to be validated.
	 */
	public $attributes;
	/**
w  
Qiang Xue committed
79 80 81 82
	 * @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
83 84 85 86 87
	 */
	public $message;
	/**
	 * @var array list of scenarios that the validator should be applied.
	 */
Qiang Xue committed
88
	public $on = array();
Qiang Xue committed
89 90 91
	/**
	 * @var array list of scenarios that the validator should not be applied to.
	 */
Qiang Xue committed
92
	public $except = array();
w  
Qiang Xue committed
93
	/**
w  
Qiang Xue committed
94
	 * @var boolean whether this validation rule should be skipped if the attribute being validated
Qiang Xue committed
95
	 * already has some validation error according to some previous rules. Defaults to true.
w  
Qiang Xue committed
96
	 */
w  
Qiang Xue committed
97
	public $skipOnError = true;
w  
Qiang Xue committed
98
	/**
Qiang Xue committed
99 100
	 * @var boolean whether to enable client-side validation. Defaults to null, meaning
	 * its actual value inherits from that of [[\yii\web\ActiveForm::enableClientValidation]].
w  
Qiang Xue committed
101
	 */
Qiang Xue committed
102
	public $enableClientValidation;
w  
Qiang Xue committed
103 104 105

	/**
	 * Validates a single attribute.
w  
Qiang Xue committed
106
	 * Child classes must implement this method to provide the actual validation logic.
Qiang Xue committed
107
	 * @param \yii\base\Model $object the data object to be validated
w  
Qiang Xue committed
108 109
	 * @param string $attribute the name of the attribute to be validated.
	 */
w  
Qiang Xue committed
110
	abstract public function validateAttribute($object, $attribute);
w  
Qiang Xue committed
111 112 113

	/**
	 * Creates a validator object.
w  
Qiang Xue committed
114
	 * @param string $type the validator type. This can be a method name,
Qiang Xue committed
115 116 117
	 * 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
118 119
	 * 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
120
	 * @return Validator the validator
w  
Qiang Xue committed
121
	 */
w  
Qiang Xue committed
122
	public static function createValidator($type, $object, $attributes, $params = array())
w  
Qiang Xue committed
123
	{
w  
Qiang Xue committed
124
		if (!is_array($attributes)) {
w  
Qiang Xue committed
125
			$attributes = preg_split('/[\s,]+/', $attributes, -1, PREG_SPLIT_NO_EMPTY);
w  
Qiang Xue committed
126
		}
Qiang Xue committed
127
		$params['attributes'] = $attributes;
w  
Qiang Xue committed
128

Qiang Xue committed
129 130
		if (isset($params['on']) && !is_array($params['on'])) {
			$params['on'] = preg_split('/[\s,]+/', $params['on'], -1, PREG_SPLIT_NO_EMPTY);
w  
Qiang Xue committed
131 132
		}

Qiang Xue committed
133 134
		if (isset($params['except']) && !is_array($params['except'])) {
			$params['except'] = preg_split('/[\s,]+/', $params['except'], -1, PREG_SPLIT_NO_EMPTY);
Qiang Xue committed
135 136
		}

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

Qiang Xue committed
154
		return \Yii::createObject($params);
w  
Qiang Xue committed
155 156 157 158
	}

	/**
	 * Validates the specified object.
w  
Qiang Xue committed
159
	 * @param \yii\base\Model $object the data object being validated
160 161 162 163
	 * @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
164 165 166
	 */
	public function validate($object, $attributes = null)
	{
w  
Qiang Xue committed
167
		if (is_array($attributes)) {
w  
Qiang Xue committed
168
			$attributes = array_intersect($this->attributes, $attributes);
Qiang Xue committed
169
		} else {
w  
Qiang Xue committed
170
			$attributes = $this->attributes;
w  
Qiang Xue committed
171 172
		}
		foreach ($attributes as $attribute) {
Qiang Xue committed
173
			if (!($this->skipOnError && $object->hasErrors($attribute))) {
w  
Qiang Xue committed
174
				$this->validateAttribute($object, $attribute);
w  
Qiang Xue committed
175
			}
w  
Qiang Xue committed
176 177 178 179 180
		}
	}

	/**
	 * Returns the JavaScript needed for performing client-side validation.
w  
Qiang Xue committed
181 182 183 184 185 186 187 188 189 190 191
	 *
	 * 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
192
	 * @param string $attribute the name of the attribute to be validated.
w  
Qiang Xue committed
193 194 195 196
	 * @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
197 198 199
	 */
	public function clientValidateAttribute($object, $attribute)
	{
Qiang Xue committed
200
		return null;
w  
Qiang Xue committed
201 202 203
	}

	/**
204 205 206
	 * Returns a value indicating whether the validator is active for the given scenario and attribute.
	 *
	 * A validator is active if
w  
Qiang Xue committed
207
	 *
208
	 * - the validator's `on` property is empty, or
w  
Qiang Xue committed
209 210
	 * - the validator's `on` property contains the specified scenario
	 *
w  
Qiang Xue committed
211 212 213
	 * @param string $scenario scenario name
	 * @return boolean whether the validator applies to the specified scenario.
	 */
Qiang Xue committed
214
	public function isActive($scenario)
w  
Qiang Xue committed
215
	{
Qiang Xue committed
216
		return !in_array($scenario, $this->except, true) && (empty($this->on) || in_array($scenario, $this->on, true));
w  
Qiang Xue committed
217 218 219
	}

	/**
w  
Qiang Xue committed
220
	 * Adds an error about the specified attribute to the model object.
w  
Qiang Xue committed
221
	 * This is a helper method that performs message selection and internationalization.
w  
Qiang Xue committed
222
	 * @param \yii\base\Model $object the data object being validated
w  
Qiang Xue committed
223 224 225 226
	 * @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
227
	public function addError($object, $attribute, $message, $params = array())
w  
Qiang Xue committed
228 229
	{
		$params['{attribute}'] = $object->getAttributeLabel($attribute);
w  
Qiang Xue committed
230
		$params['{value}'] = $object->$attribute;
w  
Qiang Xue committed
231 232 233 234 235 236 237 238 239 240 241
		$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
242
	public function isEmpty($value, $trim = false)
w  
Qiang Xue committed
243
	{
w  
Qiang Xue committed
244
		return $value === null || $value === array() || $value === ''
Qiang Xue committed
245
			|| $trim && is_scalar($value) && trim($value) === '';
w  
Qiang Xue committed
246 247
	}
}