Validator.php 19 KB

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