Validator.php 14.8 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
 * Child classes should override the [[validateValue()]] and/or [[validateAttribute()]] methods to provide the actual
Qiang Xue committed
18
 * 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
 * - `boolean`: [[BooleanValidator]]
25
 * - `captcha`: [[\yii\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
 * - `string`: [[StringValidator]]
Qiang Xue committed
41
 * - `trim`: [[FilterValidator]]
Qiang Xue committed
42 43
 * - `unique`: [[UniqueValidator]]
 * - `url`: [[UrlValidator]]
w  
Qiang Xue committed
44 45
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
w  
Qiang Xue committed
46
 * @since 2.0
w  
Qiang Xue committed
47
 */
Qiang Xue committed
48
class Validator extends Component
w  
Qiang Xue committed
49
{
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
    /**
     * @var array list of built-in validators (name => class or configuration)
     */
    public static $builtInValidators = [
        'boolean' => 'yii\validators\BooleanValidator',
        'captcha' => 'yii\captcha\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',
        'image' => 'yii\validators\ImageValidator',
        'in' => 'yii\validators\RangeValidator',
        'integer' => [
            'class' => 'yii\validators\NumberValidator',
            'integerOnly' => true,
        ],
        'match' => 'yii\validators\RegularExpressionValidator',
        'number' => 'yii\validators\NumberValidator',
        'required' => 'yii\validators\RequiredValidator',
        'safe' => 'yii\validators\SafeValidator',
        'string' => 'yii\validators\StringValidator',
        'trim' => [
            'class' => 'yii\validators\FilterValidator',
            'filter' => 'trim',
Qiang Xue committed
78
            'skipOnArray' => true,
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
        ],
        'unique' => 'yii\validators\UniqueValidator',
        'url' => 'yii\validators\UrlValidator',
    ];
    /**
     * @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.
     */
    public $attributes = [];
    /**
     * @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
Qiang Xue committed
94 95 96 97 98
     *
     * Note that some validators may introduce other properties for error messages used when specific
     * validation conditions are not met. Please refer to individual class API documentation for details
     * about these properties. By convention, this property represents the primary error message
     * used when the most important validation condition is not met.
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
     */
    public $message;
    /**
     * @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.
     */
    public $on = [];
    /**
     * @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.
     */
    public $except = [];
    /**
     * @var boolean whether this validation rule should be skipped if the attribute being validated
     * already has some validation error according to some previous rules. Defaults to true.
     */
    public $skipOnError = true;
    /**
     * @var boolean whether this validation rule should be skipped if the attribute value
     * is null or an empty string.
     */
    public $skipOnEmpty = true;
    /**
     * @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;
    /**
     * @var callable a PHP callable that replaces the default implementation of [[isEmpty()]].
     * If not set, [[isEmpty()]] will be used to check if a value is empty. The signature
     * of the callable should be `function ($value)` which returns a boolean indicating
     * whether the value is empty.
     */
    public $isEmpty;
135
    /**
Qiang Xue committed
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
     * @var callable a PHP callable whose return value determines whether this validator should be applied.
     * The signature of the callable should be `function ($model, $attribute)`, where `$model` and `$attribute`
     * refer to the model and the attribute currently being validated. The callable should return a boolean value.
     *
     * This property is mainly provided to support conditional validation on the server side.
     * If this property is not set, this validator will be always applied on the server side.
     *
     * The following example will enable the validator only when the country currently selected is USA:
     *
     * ```php
     * function ($model) {
     *     return $model->country == Country::USA;
     * }
     * ```
     *
     * @see whenClient
     */
153
    public $when;
Qiang Xue committed
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
    /**
     * @var string a JavaScript function name whose return value determines whether this validator should be applied
     * on the client side. The signature of the function should be `function (attribute, value)`, where
     * `attribute` is the name of the attribute being validated and `value` the current value of the attribute.
     *
     * This property is mainly provided to support conditional validation on the client side.
     * If this property is not set, this validator will be always applied on the client side.
     *
     * The following example will enable the validator only when the country currently selected is USA:
     *
     * ```php
     * function (attribute, value) {
     *     return $('#country').value == 'USA';
     * }
     * ```
     *
     * @see when
     */
    public $whenClient;

174

175 176
    /**
     * Creates a validator object.
177 178
     * @param mixed $type the validator type. This can be a built-in validator name,
     * a method name of the model class, an anonymous function, or a validator class name.
Qiang Xue committed
179
     * @param \yii\base\Model $model the data model to be validated.
180 181 182 183
     * @param array|string $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
     * @return Validator the validator
184
     */
Qiang Xue committed
185
    public static function createValidator($type, $model, $attributes, $params = [])
186 187
    {
        $params['attributes'] = $attributes;
w  
Qiang Xue committed
188

Qiang Xue committed
189
        if ($type instanceof \Closure || $model->hasMethod($type)) {
190 191 192 193 194 195 196 197
            // method-based validator
            $params['class'] = __NAMESPACE__ . '\InlineValidator';
            $params['method'] = $type;
        } else {
            if (isset(static::$builtInValidators[$type])) {
                $type = static::$builtInValidators[$type];
            }
            if (is_array($type)) {
Qiang Xue committed
198
                $params = array_merge($type, $params);
199 200 201 202
            } else {
                $params['class'] = $type;
            }
        }
Qiang Xue committed
203

204 205
        return Yii::createObject($params);
    }
w  
Qiang Xue committed
206

207 208 209 210 211 212 213 214 215 216
    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();
        $this->attributes = (array) $this->attributes;
        $this->on = (array) $this->on;
        $this->except = (array) $this->except;
    }
w  
Qiang Xue committed
217

218 219
    /**
     * Validates the specified object.
Qiang Xue committed
220
     * @param \yii\base\Model $model the data model being validated
221 222 223 224
     * @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.
225
     */
Qiang Xue committed
226
    public function validateAttributes($model, $attributes = null)
227 228 229 230 231 232 233
    {
        if (is_array($attributes)) {
            $attributes = array_intersect($this->attributes, $attributes);
        } else {
            $attributes = $this->attributes;
        }
        foreach ($attributes as $attribute) {
Qiang Xue committed
234 235
            $skip = $this->skipOnError && $model->hasErrors($attribute)
                || $this->skipOnEmpty && $this->isEmpty($model->$attribute);
236
            if (!$skip) {
Qiang Xue committed
237 238
                if ($this->when === null || call_user_func($this->when, $model, $attribute)) {
                    $this->validateAttribute($model, $attribute);
239
                }
240 241 242
            }
        }
    }
243

244 245 246
    /**
     * Validates a single attribute.
     * Child classes must implement this method to provide the actual validation logic.
Qiang Xue committed
247
     * @param \yii\base\Model $model the data model to be validated
248
     * @param string $attribute the name of the attribute to be validated.
249
     */
Qiang Xue committed
250
    public function validateAttribute($model, $attribute)
251
    {
Qiang Xue committed
252
        $result = $this->validateValue($model->$attribute);
253
        if (!empty($result)) {
Qiang Xue committed
254
            $this->addError($model, $attribute, $result[0], $result[1]);
255 256
        }
    }
w  
Qiang Xue committed
257

258 259 260
    /**
     * Validates a given value.
     * You may use this method to validate a value out of the context of a data model.
261 262
     * @param mixed $value the data value to be validated.
     * @param string $error the error message to be returned, if the validation fails.
263 264 265 266 267 268 269 270 271 272 273 274
     * @return boolean whether the data is valid.
     */
    public function validate($value, &$error = null)
    {
        $result = $this->validateValue($value);
        if (empty($result)) {
            return true;
        } else {
            list($message, $params) = $result;
            $params['attribute'] = Yii::t('yii', 'the input value');
            $params['value'] = is_array($value) ? 'array()' : $value;
            $error = Yii::$app->getI18n()->format($message, $params, Yii::$app->language);
Qiang Xue committed
275

276 277 278
            return false;
        }
    }
Qiang Xue committed
279

280 281 282
    /**
     * Validates a value.
     * A validator class can implement this method to support data validation out of the context of a data model.
283 284 285
     * @param mixed $value the data value to be validated.
     * @return array|null the error message and the parameters to be inserted into the error message.
     * Null should be returned if the data is valid.
286 287 288 289 290 291
     * @throws NotSupportedException if the validator does not supporting data validation without a model
     */
    protected function validateValue($value)
    {
        throw new NotSupportedException(get_class($this) . ' does not support validateValue().');
    }
Qiang Xue committed
292

293 294 295 296 297 298 299 300 301 302 303
    /**
     * Returns the JavaScript needed for performing client-side validation.
     *
     * 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.
304
     * - `deferred`: an array used to hold deferred objects for asynchronous validation
305
     *
Qiang Xue committed
306
     * @param \yii\base\Model $model the data model being validated
307 308 309 310 311
     * @param string $attribute the name of the attribute to be validated.
     * @param \yii\web\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.
     * @return string the client-side validation script. Null if the validator does not support
     * client-side validation.
312 313
     * @see \yii\widgets\ActiveForm::enableClientValidation
     */
Qiang Xue committed
314
    public function clientValidateAttribute($model, $attribute, $view)
315 316 317
    {
        return null;
    }
w  
Qiang Xue committed
318

319 320 321 322 323 324 325 326
    /**
     * Returns a value indicating whether the validator is active for the given scenario and attribute.
     *
     * A validator is active if
     *
     * - the validator's `on` property is empty, or
     * - the validator's `on` property contains the specified scenario
     *
327
     * @param string $scenario scenario name
328 329 330 331 332 333
     * @return boolean whether the validator applies to the specified scenario.
     */
    public function isActive($scenario)
    {
        return !in_array($scenario, $this->except, true) && (empty($this->on) || in_array($scenario, $this->on, true));
    }
w  
Qiang Xue committed
334

335 336 337
    /**
     * Adds an error about the specified attribute to the model object.
     * This is a helper method that performs message selection and internationalization.
Qiang Xue committed
338
     * @param \yii\base\Model $model the data model being validated
339 340 341
     * @param string $attribute the attribute being validated
     * @param string $message the error message
     * @param array $params values for the placeholders in the error message
342
     */
Qiang Xue committed
343
    public function addError($model, $attribute, $message, $params = [])
344
    {
Qiang Xue committed
345 346
        $value = $model->$attribute;
        $params['attribute'] = $model->getAttributeLabel($attribute);
347
        $params['value'] = is_array($value) ? 'array()' : $value;
Qiang Xue committed
348
        $model->addError($attribute, Yii::$app->getI18n()->format($message, $params, Yii::$app->language));
349
    }
w  
Qiang Xue committed
350

351 352 353 354
    /**
     * 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.
355
     * @param mixed $value the value to be checked
356 357 358 359 360 361 362 363 364 365
     * @return boolean whether the value is empty
     */
    public function isEmpty($value)
    {
        if ($this->isEmpty !== null) {
            return call_user_func($this->isEmpty, $value);
        } else {
            return $value === null || $value === [] || $value === '';
        }
    }
w  
Qiang Xue committed
366
}