Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

417 lines
17KB

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