PageRenderTime 46ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/framework/yii/validators/Validator.php

https://github.com/stefan321/yii2
PHP | 270 lines | 107 code | 16 blank | 147 comment | 23 complexity | 851d4423f2e630052e03ec5d664f940d 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. /**
  12. * Validator is the base class for all validators.
  13. *
  14. * Child classes should override the [[validateAttribute()]] method 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`: [[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. * - `in`: [[RangeValidator]]
  32. * - `integer`: [[NumberValidator]]
  33. * - `match`: [[RegularExpressionValidator]]
  34. * - `required`: [[RequiredValidator]]
  35. * - `string`: [[StringValidator]]
  36. * - `unique`: [[UniqueValidator]]
  37. * - `url`: [[UrlValidator]]
  38. *
  39. * @author Qiang Xue <qiang.xue@gmail.com>
  40. * @since 2.0
  41. */
  42. abstract class Validator extends Component
  43. {
  44. /**
  45. * @var array list of built-in validators (name => class or configuration)
  46. */
  47. public static $builtInValidators = array(
  48. 'boolean' => 'yii\validators\BooleanValidator',
  49. 'captcha' => 'yii\validators\CaptchaValidator',
  50. 'compare' => 'yii\validators\CompareValidator',
  51. 'date' => 'yii\validators\DateValidator',
  52. 'default' => 'yii\validators\DefaultValueValidator',
  53. 'double' => 'yii\validators\NumberValidator',
  54. 'email' => 'yii\validators\EmailValidator',
  55. 'exist' => 'yii\validators\ExistValidator',
  56. 'file' => 'yii\validators\FileValidator',
  57. 'filter' => 'yii\validators\FilterValidator',
  58. 'in' => 'yii\validators\RangeValidator',
  59. 'integer' => array(
  60. 'class' => 'yii\validators\NumberValidator',
  61. 'integerOnly' => true,
  62. ),
  63. 'match' => 'yii\validators\RegularExpressionValidator',
  64. 'number' => 'yii\validators\NumberValidator',
  65. 'required' => 'yii\validators\RequiredValidator',
  66. 'string' => 'yii\validators\StringValidator',
  67. 'unique' => 'yii\validators\UniqueValidator',
  68. 'url' => 'yii\validators\UrlValidator',
  69. );
  70. /**
  71. * @var array list of attributes to be validated.
  72. */
  73. public $attributes;
  74. /**
  75. * @var string the user-defined error message. It may contain the following placeholders which
  76. * will be replaced accordingly by the validator:
  77. *
  78. * - `{attribute}`: the label of the attribute being validated
  79. * - `{value}`: the value of the attribute being validated
  80. */
  81. public $message;
  82. /**
  83. * @var array list of scenarios that the validator can be applied to.
  84. */
  85. public $on = array();
  86. /**
  87. * @var array list of scenarios that the validator should not be applied to.
  88. */
  89. public $except = array();
  90. /**
  91. * @var boolean whether this validation rule should be skipped if the attribute being validated
  92. * already has some validation error according to some previous rules. Defaults to true.
  93. */
  94. public $skipOnError = true;
  95. /**
  96. * @var boolean whether this validation rule should be skipped if the attribute value
  97. * is null or an empty string.
  98. */
  99. public $skipOnEmpty = true;
  100. /**
  101. * @var boolean whether to enable client-side validation for this validator.
  102. * The actual client-side validation is done via the JavaScript code returned
  103. * by [[clientValidateAttribute()]]. If that method returns null, even if this property
  104. * is true, no client-side validation will be done by this validator.
  105. */
  106. public $enableClientValidation = true;
  107. /**
  108. * Validates a single attribute.
  109. * Child classes must implement this method to provide the actual validation logic.
  110. * @param \yii\base\Model $object the data object to be validated
  111. * @param string $attribute the name of the attribute to be validated.
  112. */
  113. abstract public function validateAttribute($object, $attribute);
  114. /**
  115. * Creates a validator object.
  116. * @param string $type the validator type. This can be a method name,
  117. * a built-in validator name, a class name, or a path alias of the validator class.
  118. * @param \yii\base\Model $object the data object to be validated.
  119. * @param array|string $attributes list of attributes to be validated. This can be either an array of
  120. * the attribute names or a string of comma-separated attribute names.
  121. * @param array $params initial values to be applied to the validator properties
  122. * @return Validator the validator
  123. */
  124. public static function createValidator($type, $object, $attributes, $params = array())
  125. {
  126. if (!is_array($attributes)) {
  127. $attributes = preg_split('/[\s,]+/', $attributes, -1, PREG_SPLIT_NO_EMPTY);
  128. }
  129. $params['attributes'] = $attributes;
  130. if (isset($params['on']) && !is_array($params['on'])) {
  131. $params['on'] = preg_split('/[\s,]+/', $params['on'], -1, PREG_SPLIT_NO_EMPTY);
  132. }
  133. if (isset($params['except']) && !is_array($params['except'])) {
  134. $params['except'] = preg_split('/[\s,]+/', $params['except'], -1, PREG_SPLIT_NO_EMPTY);
  135. }
  136. if (method_exists($object, $type)) {
  137. // method-based validator
  138. $params['class'] = __NAMESPACE__ . '\InlineValidator';
  139. $params['method'] = $type;
  140. } else {
  141. if (isset(self::$builtInValidators[$type])) {
  142. $type = self::$builtInValidators[$type];
  143. }
  144. if (is_array($type)) {
  145. foreach ($type as $name => $value) {
  146. $params[$name] = $value;
  147. }
  148. } else {
  149. $params['class'] = $type;
  150. }
  151. }
  152. return Yii::createObject($params);
  153. }
  154. /**
  155. * Validates the specified object.
  156. * @param \yii\base\Model $object the data object being validated
  157. * @param array|null $attributes the list of attributes to be validated.
  158. * Note that if an attribute is not associated with the validator,
  159. * it will be ignored.
  160. * If this parameter is null, every attribute listed in [[attributes]] will be validated.
  161. */
  162. public function validate($object, $attributes = null)
  163. {
  164. if (is_array($attributes)) {
  165. $attributes = array_intersect($this->attributes, $attributes);
  166. } else {
  167. $attributes = $this->attributes;
  168. }
  169. foreach ($attributes as $attribute) {
  170. $skip = $this->skipOnError && $object->hasErrors($attribute)
  171. || $this->skipOnEmpty && $this->isEmpty($object->$attribute);
  172. if (!$skip) {
  173. $this->validateAttribute($object, $attribute);
  174. }
  175. }
  176. }
  177. /**
  178. * Validates a value.
  179. * A validator class can implement this method to support data validation out of the context of a data model.
  180. * @param mixed $value the data value to be validated.
  181. * @throws NotSupportedException if data validation without a model is not supported
  182. */
  183. public function validateValue($value)
  184. {
  185. throw new NotSupportedException(get_class($this) . ' does not support validateValue().');
  186. }
  187. /**
  188. * Returns the JavaScript needed for performing client-side validation.
  189. *
  190. * You may override this method to return the JavaScript validation code if
  191. * the validator can support client-side validation.
  192. *
  193. * The following JavaScript variables are predefined and can be used in the validation code:
  194. *
  195. * - `attribute`: the name of the attribute being validated.
  196. * - `value`: the value being validated.
  197. * - `messages`: an array used to hold the validation error messages for the attribute.
  198. *
  199. * @param \yii\base\Model $object the data object being validated
  200. * @param string $attribute the name of the attribute to be validated.
  201. * @param \yii\base\View $view the view object that is going to be used to render views or view files
  202. * containing a model form with this validator applied.
  203. * @return string the client-side validation script. Null if the validator does not support
  204. * client-side validation.
  205. * @see \yii\web\ActiveForm::enableClientValidation
  206. */
  207. public function clientValidateAttribute($object, $attribute, $view)
  208. {
  209. return null;
  210. }
  211. /**
  212. * Returns a value indicating whether the validator is active for the given scenario and attribute.
  213. *
  214. * A validator is active if
  215. *
  216. * - the validator's `on` property is empty, or
  217. * - the validator's `on` property contains the specified scenario
  218. *
  219. * @param string $scenario scenario name
  220. * @return boolean whether the validator applies to the specified scenario.
  221. */
  222. public function isActive($scenario)
  223. {
  224. return !in_array($scenario, $this->except, true) && (empty($this->on) || in_array($scenario, $this->on, true));
  225. }
  226. /**
  227. * Adds an error about the specified attribute to the model object.
  228. * This is a helper method that performs message selection and internationalization.
  229. * @param \yii\base\Model $object the data object being validated
  230. * @param string $attribute the attribute being validated
  231. * @param string $message the error message
  232. * @param array $params values for the placeholders in the error message
  233. */
  234. public function addError($object, $attribute, $message, $params = array())
  235. {
  236. $value = $object->$attribute;
  237. $params['{attribute}'] = $object->getAttributeLabel($attribute);
  238. $params['{value}'] = is_array($value) ? 'array()' : $value;
  239. $object->addError($attribute, strtr($message, $params));
  240. }
  241. /**
  242. * Checks if the given value is empty.
  243. * A value is considered empty if it is null, an empty array, or the trimmed result is an empty string.
  244. * Note that this method is different from PHP empty(). It will return false when the value is 0.
  245. * @param mixed $value the value to be checked
  246. * @param boolean $trim whether to perform trimming before checking if the string is empty. Defaults to false.
  247. * @return boolean whether the value is empty
  248. */
  249. public function isEmpty($value, $trim = false)
  250. {
  251. return $value === null || $value === array() || $value === ''
  252. || $trim && is_scalar($value) && trim($value) === '';
  253. }
  254. }