You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

404 lines
16KB

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