PageRenderTime 47ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/framework/validators/Validator.php

https://gitlab.com/lcp0578/yii2
PHP | 378 lines | 137 code | 18 blank | 223 comment | 22 complexity | bc36bf7003d9df80e4251dfb42edbc0b MD5 | raw file
Possible License(s): BSD-3-Clause
  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. * - `default`: [[DefaultValueValidator]]
  26. * - `double`: [[NumberValidator]]
  27. * - `each`: [[EachValidator]]
  28. * - `email`: [[EmailValidator]]
  29. * - `exist`: [[ExistValidator]]
  30. * - `file`: [[FileValidator]]
  31. * - `filter`: [[FilterValidator]]
  32. * - `image`: [[ImageValidator]]
  33. * - `in`: [[RangeValidator]]
  34. * - `integer`: [[NumberValidator]]
  35. * - `match`: [[RegularExpressionValidator]]
  36. * - `required`: [[RequiredValidator]]
  37. * - `safe`: [[SafeValidator]]
  38. * - `string`: [[StringValidator]]
  39. * - `trim`: [[FilterValidator]]
  40. * - `unique`: [[UniqueValidator]]
  41. * - `url`: [[UrlValidator]]
  42. *
  43. * @author Qiang Xue <qiang.xue@gmail.com>
  44. * @since 2.0
  45. */
  46. class Validator extends Component
  47. {
  48. /**
  49. * @var array list of built-in validators (name => class or configuration)
  50. */
  51. public static $builtInValidators = [
  52. 'boolean' => 'yii\validators\BooleanValidator',
  53. 'captcha' => 'yii\captcha\CaptchaValidator',
  54. 'compare' => 'yii\validators\CompareValidator',
  55. 'date' => 'yii\validators\DateValidator',
  56. 'default' => 'yii\validators\DefaultValueValidator',
  57. 'double' => 'yii\validators\NumberValidator',
  58. 'each' => 'yii\validators\EachValidator',
  59. 'email' => 'yii\validators\EmailValidator',
  60. 'exist' => 'yii\validators\ExistValidator',
  61. 'file' => 'yii\validators\FileValidator',
  62. 'filter' => 'yii\validators\FilterValidator',
  63. 'image' => 'yii\validators\ImageValidator',
  64. 'in' => 'yii\validators\RangeValidator',
  65. 'integer' => [
  66. 'class' => 'yii\validators\NumberValidator',
  67. 'integerOnly' => true,
  68. ],
  69. 'match' => 'yii\validators\RegularExpressionValidator',
  70. 'number' => 'yii\validators\NumberValidator',
  71. 'required' => 'yii\validators\RequiredValidator',
  72. 'safe' => 'yii\validators\SafeValidator',
  73. 'string' => 'yii\validators\StringValidator',
  74. 'trim' => [
  75. 'class' => 'yii\validators\FilterValidator',
  76. 'filter' => 'trim',
  77. 'skipOnArray' => true,
  78. ],
  79. 'unique' => 'yii\validators\UniqueValidator',
  80. 'url' => 'yii\validators\UrlValidator',
  81. ];
  82. /**
  83. * @var array|string attributes to be validated by this validator. For multiple attributes,
  84. * please specify them as an array; for single attribute, you may use either a string or an array.
  85. */
  86. public $attributes = [];
  87. /**
  88. * @var string the user-defined error message. It may contain the following placeholders which
  89. * will be replaced accordingly by the validator:
  90. *
  91. * - `{attribute}`: the label of the attribute being validated
  92. * - `{value}`: the value of the attribute being validated
  93. *
  94. * Note that some validators may introduce other properties for error messages used when specific
  95. * validation conditions are not met. Please refer to individual class API documentation for details
  96. * about these properties. By convention, this property represents the primary error message
  97. * used when the most important validation condition is not met.
  98. */
  99. public $message;
  100. /**
  101. * @var array|string scenarios that the validator can be applied to. For multiple scenarios,
  102. * please specify them as an array; for single scenario, you may use either a string or an array.
  103. */
  104. public $on = [];
  105. /**
  106. * @var array|string scenarios that the validator should not be applied to. For multiple scenarios,
  107. * please specify them as an array; for single scenario, you may use either a string or an array.
  108. */
  109. public $except = [];
  110. /**
  111. * @var boolean whether this validation rule should be skipped if the attribute being validated
  112. * already has some validation error according to some previous rules. Defaults to true.
  113. */
  114. public $skipOnError = true;
  115. /**
  116. * @var boolean whether this validation rule should be skipped if the attribute value
  117. * is null or an empty string.
  118. */
  119. public $skipOnEmpty = true;
  120. /**
  121. * @var boolean whether to enable client-side validation for this validator.
  122. * The actual client-side validation is done via the JavaScript code returned
  123. * by [[clientValidateAttribute()]]. If that method returns null, even if this property
  124. * is true, no client-side validation will be done by this validator.
  125. */
  126. public $enableClientValidation = true;
  127. /**
  128. * @var callable a PHP callable that replaces the default implementation of [[isEmpty()]].
  129. * If not set, [[isEmpty()]] will be used to check if a value is empty. The signature
  130. * of the callable should be `function ($value)` which returns a boolean indicating
  131. * whether the value is empty.
  132. */
  133. public $isEmpty;
  134. /**
  135. * @var callable a PHP callable whose return value determines whether this validator should be applied.
  136. * The signature of the callable should be `function ($model, $attribute)`, where `$model` and `$attribute`
  137. * refer to the model and the attribute currently being validated. The callable should return a boolean value.
  138. *
  139. * This property is mainly provided to support conditional validation on the server side.
  140. * If this property is not set, this validator will be always applied on the server side.
  141. *
  142. * The following example will enable the validator only when the country currently selected is USA:
  143. *
  144. * ```php
  145. * function ($model) {
  146. * return $model->country == Country::USA;
  147. * }
  148. * ```
  149. *
  150. * @see whenClient
  151. */
  152. public $when;
  153. /**
  154. * @var string a JavaScript function name whose return value determines whether this validator should be applied
  155. * on the client side. The signature of the function should be `function (attribute, value)`, where
  156. * `attribute` is an object describing the attribute being validated (see [[clientValidateAttribute()]])
  157. * and `value` the current value of the attribute.
  158. *
  159. * This property is mainly provided to support conditional validation on the client side.
  160. * If this property is not set, this validator will be always applied on the client side.
  161. *
  162. * The following example will enable the validator only when the country currently selected is USA:
  163. *
  164. * ```php
  165. * function (attribute, value) {
  166. * return $('#country').val() === 'USA';
  167. * }
  168. * ```
  169. *
  170. * @see when
  171. */
  172. public $whenClient;
  173. /**
  174. * Creates a validator object.
  175. * @param mixed $type the validator type. This can be a built-in validator name,
  176. * a method name of the model class, an anonymous function, or a validator class name.
  177. * @param \yii\base\Model $model the data model to be validated.
  178. * @param array|string $attributes list of attributes to be validated. This can be either an array of
  179. * the attribute names or a string of comma-separated attribute names.
  180. * @param array $params initial values to be applied to the validator properties
  181. * @return Validator the validator
  182. */
  183. public static function createValidator($type, $model, $attributes, $params = [])
  184. {
  185. $params['attributes'] = $attributes;
  186. if ($type instanceof \Closure || $model->hasMethod($type)) {
  187. // method-based validator
  188. $params['class'] = __NAMESPACE__ . '\InlineValidator';
  189. $params['method'] = $type;
  190. } else {
  191. if (isset(static::$builtInValidators[$type])) {
  192. $type = static::$builtInValidators[$type];
  193. }
  194. if (is_array($type)) {
  195. $params = array_merge($type, $params);
  196. } else {
  197. $params['class'] = $type;
  198. }
  199. }
  200. return Yii::createObject($params);
  201. }
  202. /**
  203. * @inheritdoc
  204. */
  205. public function init()
  206. {
  207. parent::init();
  208. $this->attributes = (array) $this->attributes;
  209. $this->on = (array) $this->on;
  210. $this->except = (array) $this->except;
  211. }
  212. /**
  213. * Validates the specified object.
  214. * @param \yii\base\Model $model the data model being validated
  215. * @param array|null $attributes the list of attributes to be validated.
  216. * Note that if an attribute is not associated with the validator,
  217. * it will be ignored.
  218. * If this parameter is null, every attribute listed in [[attributes]] will be validated.
  219. */
  220. public function validateAttributes($model, $attributes = null)
  221. {
  222. if (is_array($attributes)) {
  223. $attributes = array_intersect($this->attributes, $attributes);
  224. } else {
  225. $attributes = $this->attributes;
  226. }
  227. foreach ($attributes as $attribute) {
  228. $skip = $this->skipOnError && $model->hasErrors($attribute)
  229. || $this->skipOnEmpty && $this->isEmpty($model->$attribute);
  230. if (!$skip) {
  231. if ($this->when === null || call_user_func($this->when, $model, $attribute)) {
  232. $this->validateAttribute($model, $attribute);
  233. }
  234. }
  235. }
  236. }
  237. /**
  238. * Validates a single attribute.
  239. * Child classes must implement this method to provide the actual validation logic.
  240. * @param \yii\base\Model $model the data model to be validated
  241. * @param string $attribute the name of the attribute to be validated.
  242. */
  243. public function validateAttribute($model, $attribute)
  244. {
  245. $result = $this->validateValue($model->$attribute);
  246. if (!empty($result)) {
  247. $this->addError($model, $attribute, $result[0], $result[1]);
  248. }
  249. }
  250. /**
  251. * Validates a given value.
  252. * You may use this method to validate a value out of the context of a data model.
  253. * @param mixed $value the data value to be validated.
  254. * @param string $error the error message to be returned, if the validation fails.
  255. * @return boolean whether the data is valid.
  256. */
  257. public function validate($value, &$error = null)
  258. {
  259. $result = $this->validateValue($value);
  260. if (empty($result)) {
  261. return true;
  262. }
  263. list($message, $params) = $result;
  264. $params['attribute'] = Yii::t('yii', 'the input value');
  265. $params['value'] = is_array($value) ? 'array()' : $value;
  266. $error = Yii::$app->getI18n()->format($message, $params, Yii::$app->language);
  267. return false;
  268. }
  269. /**
  270. * Validates a value.
  271. * A validator class can implement this method to support data validation out of the context of a data model.
  272. * @param mixed $value the data value to be validated.
  273. * @return array|null the error message and the parameters to be inserted into the error message.
  274. * Null should be returned if the data is valid.
  275. * @throws NotSupportedException if the validator does not supporting data validation without a model
  276. */
  277. protected function validateValue($value)
  278. {
  279. throw new NotSupportedException(get_class($this) . ' does not support validateValue().');
  280. }
  281. /**
  282. * Returns the JavaScript needed for performing client-side validation.
  283. *
  284. * You may override this method to return the JavaScript validation code if
  285. * the validator can support client-side validation.
  286. *
  287. * The following JavaScript variables are predefined and can be used in the validation code:
  288. *
  289. * - `attribute`: an object describing the the attribute being validated.
  290. * - `value`: the value being validated.
  291. * - `messages`: an array used to hold the validation error messages for the attribute.
  292. * - `deferred`: an array used to hold deferred objects for asynchronous validation
  293. * - `$form`: a jQuery object containing the form element
  294. *
  295. * The `attribute` object contains the following properties:
  296. * - `id`: a unique ID identifying the attribute (e.g. "loginform-username") in the form
  297. * - `name`: attribute name or expression (e.g. "[0]content" for tabular input)
  298. * - `container`: the jQuery selector of the container of the input field
  299. * - `input`: the jQuery selector of the input field under the context of the form
  300. * - `error`: the jQuery selector of the error tag under the context of the container
  301. * - `status`: status of the input field, 0: empty, not entered before, 1: validated, 2: pending validation, 3: validating
  302. *
  303. * @param \yii\base\Model $model the data model being validated
  304. * @param string $attribute the name of the attribute to be validated.
  305. * @param \yii\web\View $view the view object that is going to be used to render views or view files
  306. * containing a model form with this validator applied.
  307. * @return string the client-side validation script. Null if the validator does not support
  308. * client-side validation.
  309. * @see \yii\widgets\ActiveForm::enableClientValidation
  310. */
  311. public function clientValidateAttribute($model, $attribute, $view)
  312. {
  313. return null;
  314. }
  315. /**
  316. * Returns a value indicating whether the validator is active for the given scenario and attribute.
  317. *
  318. * A validator is active if
  319. *
  320. * - the validator's `on` property is empty, or
  321. * - the validator's `on` property contains the specified scenario
  322. *
  323. * @param string $scenario scenario name
  324. * @return boolean whether the validator applies to the specified scenario.
  325. */
  326. public function isActive($scenario)
  327. {
  328. return !in_array($scenario, $this->except, true) && (empty($this->on) || in_array($scenario, $this->on, true));
  329. }
  330. /**
  331. * Adds an error about the specified attribute to the model object.
  332. * This is a helper method that performs message selection and internationalization.
  333. * @param \yii\base\Model $model the data model being validated
  334. * @param string $attribute the attribute being validated
  335. * @param string $message the error message
  336. * @param array $params values for the placeholders in the error message
  337. */
  338. public function addError($model, $attribute, $message, $params = [])
  339. {
  340. $value = $model->$attribute;
  341. $params['attribute'] = $model->getAttributeLabel($attribute);
  342. $params['value'] = is_array($value) ? 'array()' : $value;
  343. $model->addError($attribute, Yii::$app->getI18n()->format($message, $params, Yii::$app->language));
  344. }
  345. /**
  346. * Checks if the given value is empty.
  347. * A value is considered empty if it is null, an empty array, or an empty string.
  348. * Note that this method is different from PHP empty(). It will return false when the value is 0.
  349. * @param mixed $value the value to be checked
  350. * @return boolean whether the value is empty
  351. */
  352. public function isEmpty($value)
  353. {
  354. if ($this->isEmpty !== null) {
  355. return call_user_func($this->isEmpty, $value);
  356. } else {
  357. return $value === null || $value === [] || $value === '';
  358. }
  359. }
  360. }