PageRenderTime 25ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/framework/validators/Validator.php

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