Validator.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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|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. if (is_array($attributes)) {
  241. $newAttributes = [];
  242. $attributeNames = $this->getAttributeNames();
  243. foreach ($attributes as $attribute) {
  244. if (in_array($attribute, $attributeNames, true)) {
  245. $newAttributes[] = $attribute;
  246. }
  247. }
  248. $attributes = $newAttributes;
  249. } else {
  250. $attributes = $this->getAttributeNames();
  251. }
  252. foreach ($attributes as $attribute) {
  253. $skip = $this->skipOnError && $model->hasErrors($attribute)
  254. || $this->skipOnEmpty && $this->isEmpty($model->$attribute);
  255. if (!$skip) {
  256. if ($this->when === null || call_user_func($this->when, $model, $attribute)) {
  257. $this->validateAttribute($model, $attribute);
  258. }
  259. }
  260. }
  261. }
  262. /**
  263. * Validates a single attribute.
  264. * Child classes must implement this method to provide the actual validation logic.
  265. * @param \yii\base\Model $model the data model to be validated
  266. * @param string $attribute the name of the attribute to be validated.
  267. */
  268. public function validateAttribute($model, $attribute)
  269. {
  270. $result = $this->validateValue($model->$attribute);
  271. if (!empty($result)) {
  272. $this->addError($model, $attribute, $result[0], $result[1]);
  273. }
  274. }
  275. /**
  276. * Validates a given value.
  277. * You may use this method to validate a value out of the context of a data model.
  278. * @param mixed $value the data value to be validated.
  279. * @param string $error the error message to be returned, if the validation fails.
  280. * @return bool whether the data is valid.
  281. */
  282. public function validate($value, &$error = null)
  283. {
  284. $result = $this->validateValue($value);
  285. if (empty($result)) {
  286. return true;
  287. }
  288. list($message, $params) = $result;
  289. $params['attribute'] = Yii::t('yii', 'the input value');
  290. if (is_array($value)) {
  291. $params['value'] = 'array()';
  292. } elseif (is_object($value)) {
  293. $params['value'] = 'object';
  294. } else {
  295. $params['value'] = $value;
  296. }
  297. $error = $this->formatMessage($message, $params);
  298. return false;
  299. }
  300. /**
  301. * Validates a value.
  302. * A validator class can implement this method to support data validation out of the context of a data model.
  303. * @param mixed $value the data value to be validated.
  304. * @return array|null the error message and the array of parameters to be inserted into the error message.
  305. * ```php
  306. * if (!$valid) {
  307. * return [$this->message, [
  308. * 'param1' => $this->param1,
  309. * 'formattedLimit' => Yii::$app->formatter->asShortSize($this->getSizeLimit()),
  310. * 'mimeTypes' => implode(', ', $this->mimeTypes),
  311. * 'param4' => 'etc...',
  312. * ]];
  313. * }
  314. *
  315. * return null;
  316. * ```
  317. * for this example `message` template can contain `{param1}`, `{formattedLimit}`, `{mimeTypes}`, `{param4}`
  318. *
  319. * Null should be returned if the data is valid.
  320. * @throws NotSupportedException if the validator does not supporting data validation without a model
  321. */
  322. protected function validateValue($value)
  323. {
  324. throw new NotSupportedException(get_class($this) . ' does not support validateValue().');
  325. }
  326. /**
  327. * Returns the JavaScript needed for performing client-side validation.
  328. *
  329. * Calls [[getClientOptions()]] to generate options array for client-side validation.
  330. *
  331. * You may override this method to return the JavaScript validation code if
  332. * the validator can support client-side validation.
  333. *
  334. * The following JavaScript variables are predefined and can be used in the validation code:
  335. *
  336. * - `attribute`: an object describing the the attribute being validated.
  337. * - `value`: the value being validated.
  338. * - `messages`: an array used to hold the validation error messages for the attribute.
  339. * - `deferred`: an array used to hold deferred objects for asynchronous validation
  340. * - `$form`: a jQuery object containing the form element
  341. *
  342. * The `attribute` object contains the following properties:
  343. * - `id`: a unique ID identifying the attribute (e.g. "loginform-username") in the form
  344. * - `name`: attribute name or expression (e.g. "[0]content" for tabular input)
  345. * - `container`: the jQuery selector of the container of the input field
  346. * - `input`: the jQuery selector of the input field under the context of the form
  347. * - `error`: the jQuery selector of the error tag under the context of the container
  348. * - `status`: status of the input field, 0: empty, not entered before, 1: validated, 2: pending validation, 3: validating
  349. *
  350. * @param \yii\base\Model $model the data model being validated
  351. * @param string $attribute the name of the attribute to be validated.
  352. * @param \yii\web\View $view the view object that is going to be used to render views or view files
  353. * containing a model form with this validator applied.
  354. * @return string|null the client-side validation script. Null if the validator does not support
  355. * client-side validation.
  356. * @see getClientOptions()
  357. * @see \yii\widgets\ActiveForm::enableClientValidation
  358. */
  359. public function clientValidateAttribute($model, $attribute, $view)
  360. {
  361. return null;
  362. }
  363. /**
  364. * Returns the client-side validation options.
  365. * This method is usually called from [[clientValidateAttribute()]]. You may override this method to modify options
  366. * that will be passed to the client-side validation.
  367. * @param \yii\base\Model $model the model being validated
  368. * @param string $attribute the attribute name being validated
  369. * @return array the client-side validation options
  370. * @since 2.0.11
  371. */
  372. public function getClientOptions($model, $attribute)
  373. {
  374. return [];
  375. }
  376. /**
  377. * Returns a value indicating whether the validator is active for the given scenario and attribute.
  378. *
  379. * A validator is active if
  380. *
  381. * - the validator's `on` property is empty, or
  382. * - the validator's `on` property contains the specified scenario
  383. *
  384. * @param string $scenario scenario name
  385. * @return bool whether the validator applies to the specified scenario.
  386. */
  387. public function isActive($scenario)
  388. {
  389. return !in_array($scenario, $this->except, true) && (empty($this->on) || in_array($scenario, $this->on, true));
  390. }
  391. /**
  392. * Adds an error about the specified attribute to the model object.
  393. * This is a helper method that performs message selection and internationalization.
  394. * @param \yii\base\Model $model the data model being validated
  395. * @param string $attribute the attribute being validated
  396. * @param string $message the error message
  397. * @param array $params values for the placeholders in the error message
  398. */
  399. public function addError($model, $attribute, $message, $params = [])
  400. {
  401. $params['attribute'] = $model->getAttributeLabel($attribute);
  402. if (!isset($params['value'])) {
  403. $value = $model->$attribute;
  404. if (is_array($value)) {
  405. $params['value'] = 'array()';
  406. } elseif (is_object($value) && !method_exists($value, '__toString')) {
  407. $params['value'] = '(object)';
  408. } else {
  409. $params['value'] = $value;
  410. }
  411. }
  412. $model->addError($attribute, $this->formatMessage($message, $params));
  413. }
  414. /**
  415. * Checks if the given value is empty.
  416. * A value is considered empty if it is null, an empty array, or an empty string.
  417. * Note that this method is different from PHP empty(). It will return false when the value is 0.
  418. * @param mixed $value the value to be checked
  419. * @return bool whether the value is empty
  420. */
  421. public function isEmpty($value)
  422. {
  423. if ($this->isEmpty !== null) {
  424. return call_user_func($this->isEmpty, $value);
  425. }
  426. return $value === null || $value === [] || $value === '';
  427. }
  428. /**
  429. * Formats a mesage using the I18N, or simple strtr if `\Yii::$app` is not available.
  430. * @param string $message
  431. * @param array $params
  432. * @since 2.0.12
  433. * @return string
  434. */
  435. protected function formatMessage($message, $params)
  436. {
  437. if (Yii::$app !== null) {
  438. return \Yii::$app->getI18n()->format($message, $params, Yii::$app->language);
  439. }
  440. $placeholders = [];
  441. foreach ((array) $params as $name => $value) {
  442. $placeholders['{' . $name . '}'] = $value;
  443. }
  444. return ($placeholders === []) ? $message : strtr($message, $placeholders);
  445. }
  446. /**
  447. * Returns cleaned attribute names without the `!` character at the beginning.
  448. * @return array attribute names.
  449. * @since 2.0.12
  450. */
  451. public function getAttributeNames()
  452. {
  453. return array_map(function ($attribute) {
  454. return ltrim($attribute, '!');
  455. }, $this->attributes);
  456. }
  457. }