Validator.php 18 KB

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