Validator.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\validators;
  8. use Yii;
  9. use yii\base\Component;
  10. use yii\base\NotSupportedException;
  11. /**
  12. * Validator is the base class for all validators.
  13. *
  14. * Child classes should override the [[validateValue()]] and/or [[validateAttribute()]] methods to provide the actual
  15. * logic of performing data validation. Child classes may also override [[clientValidateAttribute()]]
  16. * to provide client-side validation support.
  17. *
  18. * Validator declares a set of [[builtInValidators|built-in validators]] which can
  19. * be referenced using short names. They are listed as follows:
  20. *
  21. * - `boolean`: [[BooleanValidator]]
  22. * - `captcha`: [[\yii\captcha\CaptchaValidator]]
  23. * - `compare`: [[CompareValidator]]
  24. * - `date`: [[DateValidator]]
  25. * - `datetime`: [[DateValidator]]
  26. * - `time`: [[DateValidator]]
  27. * - `default`: [[DefaultValueValidator]]
  28. * - `double`: [[NumberValidator]]
  29. * - `each`: [[EachValidator]]
  30. * - `email`: [[EmailValidator]]
  31. * - `exist`: [[ExistValidator]]
  32. * - `file`: [[FileValidator]]
  33. * - `filter`: [[FilterValidator]]
  34. * - `image`: [[ImageValidator]]
  35. * - `in`: [[RangeValidator]]
  36. * - `integer`: [[NumberValidator]]
  37. * - `match`: [[RegularExpressionValidator]]
  38. * - `required`: [[RequiredValidator]]
  39. * - `safe`: [[SafeValidator]]
  40. * - `string`: [[StringValidator]]
  41. * - `trim`: [[FilterValidator]]
  42. * - `unique`: [[UniqueValidator]]
  43. * - `url`: [[UrlValidator]]
  44. * - `ip`: [[IpValidator]]
  45. *
  46. * For more details and usage information on Validator, see the [guide article on validators](guide:input-validation).
  47. *
  48. * @property array $attributeNames Attribute names. This property is read-only.
  49. * @property array $validationAttributes List of attribute names. This property is read-only.
  50. *
  51. * @author Qiang Xue <qiang.xue@gmail.com>
  52. * @since 2.0
  53. */
  54. class Validator extends Component
  55. {
  56. /**
  57. * @var array list of built-in validators (name => class or configuration)
  58. */
  59. public static $builtInValidators = [
  60. 'boolean' => 'yii\validators\BooleanValidator',
  61. 'captcha' => 'yii\captcha\CaptchaValidator',
  62. 'compare' => 'yii\validators\CompareValidator',
  63. 'date' => 'yii\validators\DateValidator',
  64. 'datetime' => [
  65. 'class' => 'yii\validators\DateValidator',
  66. 'type' => DateValidator::TYPE_DATETIME,
  67. ],
  68. 'time' => [
  69. 'class' => 'yii\validators\DateValidator',
  70. 'type' => DateValidator::TYPE_TIME,
  71. ],
  72. 'default' => 'yii\validators\DefaultValueValidator',
  73. 'double' => 'yii\validators\NumberValidator',
  74. 'each' => 'yii\validators\EachValidator',
  75. 'email' => 'yii\validators\EmailValidator',
  76. 'exist' => 'yii\validators\ExistValidator',
  77. 'file' => 'yii\validators\FileValidator',
  78. 'filter' => 'yii\validators\FilterValidator',
  79. 'image' => 'yii\validators\ImageValidator',
  80. 'in' => 'yii\validators\RangeValidator',
  81. 'integer' => [
  82. 'class' => 'yii\validators\NumberValidator',
  83. 'integerOnly' => true,
  84. ],
  85. 'match' => 'yii\validators\RegularExpressionValidator',
  86. 'number' => 'yii\validators\NumberValidator',
  87. 'required' => 'yii\validators\RequiredValidator',
  88. 'safe' => 'yii\validators\SafeValidator',
  89. 'string' => 'yii\validators\StringValidator',
  90. 'trim' => [
  91. 'class' => 'yii\validators\FilterValidator',
  92. 'filter' => 'trim',
  93. 'skipOnArray' => true,
  94. ],
  95. 'unique' => 'yii\validators\UniqueValidator',
  96. 'url' => 'yii\validators\UrlValidator',
  97. 'ip' => 'yii\validators\IpValidator',
  98. ];
  99. /**
  100. * @var array|string attributes to be validated by this validator. For multiple attributes,
  101. * please specify them as an array; for single attribute, you may use either a string or an array.
  102. */
  103. public $attributes = [];
  104. /**
  105. * @var string the user-defined error message. It may contain the following placeholders which
  106. * will be replaced accordingly by the validator:
  107. *
  108. * - `{attribute}`: the label of the attribute being validated
  109. * - `{value}`: the value of the attribute being validated
  110. *
  111. * Note that some validators may introduce other properties for error messages used when specific
  112. * validation conditions are not met. Please refer to individual class API documentation for details
  113. * about these properties. By convention, this property represents the primary error message
  114. * used when the most important validation condition is not met.
  115. */
  116. public $message;
  117. /**
  118. * @var array|string scenarios that the validator can be applied to. For multiple scenarios,
  119. * please specify them as an array; for single scenario, you may use either a string or an array.
  120. */
  121. public $on = [];
  122. /**
  123. * @var array|string scenarios that the validator should not be applied to. For multiple scenarios,
  124. * please specify them as an array; for single scenario, you may use either a string or an array.
  125. */
  126. public $except = [];
  127. /**
  128. * @var bool whether this validation rule should be skipped if the attribute being validated
  129. * already has some validation error according to some previous rules. Defaults to true.
  130. */
  131. public $skipOnError = true;
  132. /**
  133. * @var bool whether this validation rule should be skipped if the attribute value
  134. * is null or an empty string. This property is used only when validating [[yii\base\Model]].
  135. */
  136. public $skipOnEmpty = true;
  137. /**
  138. * @var bool whether to enable client-side validation for this validator.
  139. * The actual client-side validation is done via the JavaScript code returned
  140. * by [[clientValidateAttribute()]]. If that method returns null, even if this property
  141. * is true, no client-side validation will be done by this validator.
  142. */
  143. public $enableClientValidation = true;
  144. /**
  145. * @var callable a PHP callable that replaces the default implementation of [[isEmpty()]].
  146. * If not set, [[isEmpty()]] will be used to check if a value is empty. The signature
  147. * of the callable should be `function ($value)` which returns a boolean indicating
  148. * whether the value is empty.
  149. */
  150. public $isEmpty;
  151. /**
  152. * @var callable a PHP callable whose return value determines whether this validator should be applied.
  153. * The signature of the callable should be `function ($model, $attribute)`, where `$model` and `$attribute`
  154. * refer to the model and the attribute currently being validated. The callable should return a boolean value.
  155. *
  156. * This property is mainly provided to support conditional validation on the server-side.
  157. * If this property is not set, this validator will be always applied on the server-side.
  158. *
  159. * The following example will enable the validator only when the country currently selected is USA:
  160. *
  161. * ```php
  162. * function ($model) {
  163. * return $model->country == Country::USA;
  164. * }
  165. * ```
  166. *
  167. * @see whenClient
  168. */
  169. public $when;
  170. /**
  171. * @var string a JavaScript function name whose return value determines whether this validator should be applied
  172. * on the client-side. The signature of the function should be `function (attribute, value)`, where
  173. * `attribute` is an object describing the attribute being validated (see [[clientValidateAttribute()]])
  174. * and `value` the current value of the attribute.
  175. *
  176. * This property is mainly provided to support conditional validation on the client-side.
  177. * If this property is not set, this validator will be always applied on the client-side.
  178. *
  179. * The following example will enable the validator only when the country currently selected is USA:
  180. *
  181. * ```javascript
  182. * function (attribute, value) {
  183. * return $('#country').val() === 'USA';
  184. * }
  185. * ```
  186. *
  187. * @see when
  188. */
  189. public $whenClient;
  190. /**
  191. * Creates a validator object.
  192. * @param string|\Closure $type the validator type. This can be either:
  193. * * a built-in validator name listed in [[builtInValidators]];
  194. * * a method name of the model class;
  195. * * an anonymous function;
  196. * * a validator class name.
  197. * @param \yii\base\Model $model the data model to be validated.
  198. * @param array|string $attributes list of attributes to be validated. This can be either an array of
  199. * the attribute names or a string of comma-separated attribute names.
  200. * @param array $params initial values to be applied to the validator properties.
  201. * @return Validator the validator
  202. */
  203. public static function createValidator($type, $model, $attributes, $params = [])
  204. {
  205. $params['attributes'] = $attributes;
  206. if ($type instanceof \Closure || ($model->hasMethod($type) && !isset(static::$builtInValidators[$type]))) {
  207. // method-based validator
  208. $params['class'] = __NAMESPACE__ . '\InlineValidator';
  209. $params['method'] = $type;
  210. } else {
  211. if (isset(static::$builtInValidators[$type])) {
  212. $type = static::$builtInValidators[$type];
  213. }
  214. if (is_array($type)) {
  215. $params = array_merge($type, $params);
  216. } else {
  217. $params['class'] = $type;
  218. }
  219. }
  220. return Yii::createObject($params);
  221. }
  222. /**
  223. * {@inheritdoc}
  224. */
  225. public function init()
  226. {
  227. parent::init();
  228. $this->attributes = (array) $this->attributes;
  229. $this->on = (array) $this->on;
  230. $this->except = (array) $this->except;
  231. }
  232. /**
  233. * Validates the specified object.
  234. * @param \yii\base\Model $model the data model being validated
  235. * @param array|string|null $attributes the list of attributes to be validated.
  236. * Note that if an attribute is not associated with the validator - it will be
  237. * ignored. If this parameter is null, every attribute listed in [[attributes]] will be validated.
  238. */
  239. public function validateAttributes($model, $attributes = null)
  240. {
  241. $attributes = $this->getValidationAttributes($attributes);
  242. foreach ($attributes as $attribute) {
  243. $skip = $this->skipOnError && $model->hasErrors($attribute)
  244. || $this->skipOnEmpty && $this->isEmpty($model->$attribute);
  245. if (!$skip) {
  246. if ($this->when === null || call_user_func($this->when, $model, $attribute)) {
  247. $this->validateAttribute($model, $attribute);
  248. }
  249. }
  250. }
  251. }
  252. /**
  253. * Returns a list of attributes this validator applies to.
  254. * @param array|string|null $attributes the list of attributes to be validated.
  255. *
  256. * - If this is `null`, the result will be equal to [[getAttributeNames()]].
  257. * - If this is a string or an array, the intersection of [[getAttributeNames()]]
  258. * and the specified attributes will be returned.
  259. *
  260. * @return array list of attribute names.
  261. * @since 2.0.16
  262. */
  263. public function getValidationAttributes($attributes = null)
  264. {
  265. if ($attributes === null) {
  266. return $this->getAttributeNames();
  267. }
  268. if (is_scalar($attributes)) {
  269. $attributes = [$attributes];
  270. }
  271. $newAttributes = [];
  272. $attributeNames = $this->getAttributeNames();
  273. foreach ($attributes as $attribute) {
  274. // do not strict compare, otherwise int attributes would fail due to to string conversion in getAttributeNames() using ltrim().
  275. if (in_array($attribute, $attributeNames, false)) {
  276. $newAttributes[] = $attribute;
  277. }
  278. }
  279. return $newAttributes;
  280. }
  281. /**
  282. * Validates a single attribute.
  283. * Child classes must implement this method to provide the actual validation logic.
  284. * @param \yii\base\Model $model the data model to be validated
  285. * @param string $attribute the name of the attribute to be validated.
  286. */
  287. public function validateAttribute($model, $attribute)
  288. {
  289. $result = $this->validateValue($model->$attribute);
  290. if (!empty($result)) {
  291. $this->addError($model, $attribute, $result[0], $result[1]);
  292. }
  293. }
  294. /**
  295. * Validates a given value.
  296. * You may use this method to validate a value out of the context of a data model.
  297. * @param mixed $value the data value to be validated.
  298. * @param string $error the error message to be returned, if the validation fails.
  299. * @return bool whether the data is valid.
  300. */
  301. public function validate($value, &$error = null)
  302. {
  303. $result = $this->validateValue($value);
  304. if (empty($result)) {
  305. return true;
  306. }
  307. list($message, $params) = $result;
  308. $params['attribute'] = Yii::t('yii', 'the input value');
  309. if (is_array($value)) {
  310. $params['value'] = 'array()';
  311. } elseif (is_object($value)) {
  312. $params['value'] = 'object';
  313. } else {
  314. $params['value'] = $value;
  315. }
  316. $error = $this->formatMessage($message, $params);
  317. return false;
  318. }
  319. /**
  320. * Validates a value.
  321. * A validator class can implement this method to support data validation out of the context of a data model.
  322. * @param mixed $value the data value to be validated.
  323. * @return array|null the error message and the array of parameters to be inserted into the error message.
  324. * ```php
  325. * if (!$valid) {
  326. * return [$this->message, [
  327. * 'param1' => $this->param1,
  328. * 'formattedLimit' => Yii::$app->formatter->asShortSize($this->getSizeLimit()),
  329. * 'mimeTypes' => implode(', ', $this->mimeTypes),
  330. * 'param4' => 'etc...',
  331. * ]];
  332. * }
  333. *
  334. * return null;
  335. * ```
  336. * for this example `message` template can contain `{param1}`, `{formattedLimit}`, `{mimeTypes}`, `{param4}`
  337. *
  338. * Null should be returned if the data is valid.
  339. * @throws NotSupportedException if the validator does not supporting data validation without a model
  340. */
  341. protected function validateValue($value)
  342. {
  343. throw new NotSupportedException(get_class($this) . ' does not support validateValue().');
  344. }
  345. /**
  346. * Returns the JavaScript needed for performing client-side validation.
  347. *
  348. * Calls [[getClientOptions()]] to generate options array for client-side validation.
  349. *
  350. * You may override this method to return the JavaScript validation code if
  351. * the validator can support client-side validation.
  352. *
  353. * The following JavaScript variables are predefined and can be used in the validation code:
  354. *
  355. * - `attribute`: an object describing the the attribute being validated.
  356. * - `value`: the value being validated.
  357. * - `messages`: an array used to hold the validation error messages for the attribute.
  358. * - `deferred`: an array used to hold deferred objects for asynchronous validation
  359. * - `$form`: a jQuery object containing the form element
  360. *
  361. * The `attribute` object contains the following properties:
  362. * - `id`: a unique ID identifying the attribute (e.g. "loginform-username") in the form
  363. * - `name`: attribute name or expression (e.g. "[0]content" for tabular input)
  364. * - `container`: the jQuery selector of the container of the input field
  365. * - `input`: the jQuery selector of the input field under the context of the form
  366. * - `error`: the jQuery selector of the error tag under the context of the container
  367. * - `status`: status of the input field, 0: empty, not entered before, 1: validated, 2: pending validation, 3: validating
  368. *
  369. * @param \yii\base\Model $model the data model being validated
  370. * @param string $attribute the name of the attribute to be validated.
  371. * @param \yii\web\View $view the view object that is going to be used to render views or view files
  372. * containing a model form with this validator applied.
  373. * @return string|null the client-side validation script. Null if the validator does not support
  374. * client-side validation.
  375. * @see getClientOptions()
  376. * @see \yii\widgets\ActiveForm::enableClientValidation
  377. */
  378. public function clientValidateAttribute($model, $attribute, $view)
  379. {
  380. return null;
  381. }
  382. /**
  383. * Returns the client-side validation options.
  384. * This method is usually called from [[clientValidateAttribute()]]. You may override this method to modify options
  385. * that will be passed to the client-side validation.
  386. * @param \yii\base\Model $model the model being validated
  387. * @param string $attribute the attribute name being validated
  388. * @return array the client-side validation options
  389. * @since 2.0.11
  390. */
  391. public function getClientOptions($model, $attribute)
  392. {
  393. return [];
  394. }
  395. /**
  396. * Returns a value indicating whether the validator is active for the given scenario and attribute.
  397. *
  398. * A validator is active if
  399. *
  400. * - the validator's `on` property is empty, or
  401. * - the validator's `on` property contains the specified scenario
  402. *
  403. * @param string $scenario scenario name
  404. * @return bool whether the validator applies to the specified scenario.
  405. */
  406. public function isActive($scenario)
  407. {
  408. return !in_array($scenario, $this->except, true) && (empty($this->on) || in_array($scenario, $this->on, true));
  409. }
  410. /**
  411. * Adds an error about the specified attribute to the model object.
  412. * This is a helper method that performs message selection and internationalization.
  413. * @param \yii\base\Model $model the data model being validated
  414. * @param string $attribute the attribute being validated
  415. * @param string $message the error message
  416. * @param array $params values for the placeholders in the error message
  417. */
  418. public function addError($model, $attribute, $message, $params = [])
  419. {
  420. $params['attribute'] = $model->getAttributeLabel($attribute);
  421. if (!isset($params['value'])) {
  422. $value = $model->$attribute;
  423. if (is_array($value)) {
  424. $params['value'] = 'array()';
  425. } elseif (is_object($value) && !method_exists($value, '__toString')) {
  426. $params['value'] = '(object)';
  427. } else {
  428. $params['value'] = $value;
  429. }
  430. }
  431. $model->addError($attribute, $this->formatMessage($message, $params));
  432. }
  433. /**
  434. * Checks if the given value is empty.
  435. * A value is considered empty if it is null, an empty array, or an empty string.
  436. * Note that this method is different from PHP empty(). It will return false when the value is 0.
  437. * @param mixed $value the value to be checked
  438. * @return bool whether the value is empty
  439. */
  440. public function isEmpty($value)
  441. {
  442. if ($this->isEmpty !== null) {
  443. return call_user_func($this->isEmpty, $value);
  444. }
  445. return $value === null || $value === [] || $value === '';
  446. }
  447. /**
  448. * Formats a mesage using the I18N, or simple strtr if `\Yii::$app` is not available.
  449. * @param string $message
  450. * @param array $params
  451. * @since 2.0.12
  452. * @return string
  453. */
  454. protected function formatMessage($message, $params)
  455. {
  456. if (Yii::$app !== null) {
  457. return \Yii::$app->getI18n()->format($message, $params, Yii::$app->language);
  458. }
  459. $placeholders = [];
  460. foreach ((array) $params as $name => $value) {
  461. $placeholders['{' . $name . '}'] = $value;
  462. }
  463. return ($placeholders === []) ? $message : strtr($message, $placeholders);
  464. }
  465. /**
  466. * Returns cleaned attribute names without the `!` character at the beginning.
  467. * @return array attribute names.
  468. * @since 2.0.12
  469. */
  470. public function getAttributeNames()
  471. {
  472. return array_map(function ($attribute) {
  473. return ltrim($attribute, '!');
  474. }, $this->attributes);
  475. }
  476. }