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.

367 lines
15KB

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