CValidator.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. <?php
  2. /**
  3. * CValidator class file.
  4. *
  5. * @author Qiang Xue <qiang.xue@gmail.com>
  6. * @link http://www.yiiframework.com/
  7. * @copyright 2008-2013 Yii Software LLC
  8. * @license http://www.yiiframework.com/license/
  9. */
  10. /**
  11. * CValidator is the base class for all validators.
  12. *
  13. * Child classes must implement the {@link validateAttribute} method.
  14. *
  15. * When using {@link createValidator} to create a validator, the following aliases
  16. * are recognized as the corresponding built-in validator classes:
  17. * <ul>
  18. * <li>required: {@link CRequiredValidator}</li>
  19. * <li>filter: {@link CFilterValidator}</li>
  20. * <li>match: {@link CRegularExpressionValidator}</li>
  21. * <li>email: {@link CEmailValidator}</li>
  22. * <li>url: {@link CUrlValidator}</li>
  23. * <li>unique: {@link CUniqueValidator}</li>
  24. * <li>compare: {@link CCompareValidator}</li>
  25. * <li>length: {@link CStringValidator}</li>
  26. * <li>in: {@link CRangeValidator}</li>
  27. * <li>numerical: {@link CNumberValidator}</li>
  28. * <li>captcha: {@link CCaptchaValidator}</li>
  29. * <li>type: {@link CTypeValidator}</li>
  30. * <li>file: {@link CFileValidator}</li>
  31. * <li>default: {@link CDefaultValueValidator}</li>
  32. * <li>exist: {@link CExistValidator}</li>
  33. * <li>boolean: {@link CBooleanValidator}</li>
  34. * <li>date: {@link CDateValidator}</li>
  35. * <li>safe: {@link CSafeValidator}</li>
  36. * <li>unsafe: {@link CUnsafeValidator}</li>
  37. * </ul>
  38. *
  39. * @author Qiang Xue <qiang.xue@gmail.com>
  40. * @package system.validators
  41. * @since 1.0
  42. */
  43. abstract class CValidator extends CComponent
  44. {
  45. /**
  46. * @var array list of built-in validators (name=>class)
  47. */
  48. public static $builtInValidators=array(
  49. 'required'=>'CRequiredValidator',
  50. 'filter'=>'CFilterValidator',
  51. 'match'=>'CRegularExpressionValidator',
  52. 'email'=>'CEmailValidator',
  53. 'url'=>'CUrlValidator',
  54. 'unique'=>'CUniqueValidator',
  55. 'compare'=>'CCompareValidator',
  56. 'length'=>'CStringValidator',
  57. 'in'=>'CRangeValidator',
  58. 'numerical'=>'CNumberValidator',
  59. 'captcha'=>'CCaptchaValidator',
  60. 'type'=>'CTypeValidator',
  61. 'file'=>'CFileValidator',
  62. 'default'=>'CDefaultValueValidator',
  63. 'exist'=>'CExistValidator',
  64. 'boolean'=>'CBooleanValidator',
  65. 'safe'=>'CSafeValidator',
  66. 'unsafe'=>'CUnsafeValidator',
  67. 'date'=>'CDateValidator',
  68. );
  69. /**
  70. * @var array list of attributes to be validated.
  71. */
  72. public $attributes;
  73. /**
  74. * @var string the user-defined error message. Different validators may define various
  75. * placeholders in the message that are to be replaced with actual values. All validators
  76. * recognize "{attribute}" placeholder, which will be replaced with the label of the attribute.
  77. */
  78. public $message;
  79. /**
  80. * @var boolean whether this validation rule should be skipped when there is already a validation
  81. * error for the current attribute. Defaults to false.
  82. * @since 1.1.1
  83. */
  84. public $skipOnError=false;
  85. /**
  86. * @var array list of scenarios that the validator should be applied.
  87. * Each array value refers to a scenario name with the same name as its array key.
  88. */
  89. public $on;
  90. /**
  91. * @var array list of scenarios that the validator should not be applied to.
  92. * Each array value refers to a scenario name with the same name as its array key.
  93. * @since 1.1.11
  94. */
  95. public $except;
  96. /**
  97. * @var boolean whether attributes listed with this validator should be considered safe for massive assignment.
  98. * Defaults to true.
  99. * @since 1.1.4
  100. */
  101. public $safe=true;
  102. /**
  103. * @var boolean whether to perform client-side validation. Defaults to true.
  104. * Please refer to {@link CActiveForm::enableClientValidation} for more details about client-side validation.
  105. * @since 1.1.7
  106. */
  107. public $enableClientValidation=true;
  108. /**
  109. * Validates a single attribute.
  110. * This method should be overridden by child classes.
  111. * @param CModel $object the data object being validated
  112. * @param string $attribute the name of the attribute to be validated.
  113. */
  114. abstract protected function validateAttribute($object,$attribute);
  115. /**
  116. * Creates a validator object.
  117. * @param string $name the name or class of the validator
  118. * @param CModel $object the data object being validated that may contain the inline validation method
  119. * @param mixed $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 CValidator the validator
  123. */
  124. public static function createValidator($name,$object,$attributes,$params=array())
  125. {
  126. if(is_string($attributes))
  127. $attributes=preg_split('/\s*,\s*/',$attributes,-1,PREG_SPLIT_NO_EMPTY);
  128. if(isset($params['on']))
  129. {
  130. if(is_array($params['on']))
  131. $on=$params['on'];
  132. else
  133. $on=preg_split('/[\s,]+/',$params['on'],-1,PREG_SPLIT_NO_EMPTY);
  134. }
  135. else
  136. $on=array();
  137. if(isset($params['except']))
  138. {
  139. if(is_array($params['except']))
  140. $except=$params['except'];
  141. else
  142. $except=preg_split('/[\s,]+/',$params['except'],-1,PREG_SPLIT_NO_EMPTY);
  143. }
  144. else
  145. $except=array();
  146. if(method_exists($object,$name))
  147. {
  148. $validator=new CInlineValidator;
  149. $validator->attributes=$attributes;
  150. $validator->method=$name;
  151. if(isset($params['clientValidate']))
  152. {
  153. $validator->clientValidate=$params['clientValidate'];
  154. unset($params['clientValidate']);
  155. }
  156. $validator->params=$params;
  157. if(isset($params['skipOnError']))
  158. $validator->skipOnError=$params['skipOnError'];
  159. }
  160. else
  161. {
  162. $params['attributes']=$attributes;
  163. if(isset(self::$builtInValidators[$name]))
  164. $className=Yii::import(self::$builtInValidators[$name],true);
  165. else
  166. $className=Yii::import($name,true);
  167. $validator=new $className;
  168. foreach($params as $name=>$value)
  169. $validator->$name=$value;
  170. }
  171. $validator->on=empty($on) ? array() : array_combine($on,$on);
  172. $validator->except=empty($except) ? array() : array_combine($except,$except);
  173. return $validator;
  174. }
  175. /**
  176. * Validates the specified object.
  177. * @param CModel $object the data object being validated
  178. * @param array $attributes the list of attributes to be validated. Defaults to null,
  179. * meaning every attribute listed in {@link attributes} will be validated.
  180. */
  181. public function validate($object,$attributes=null)
  182. {
  183. if(is_array($attributes))
  184. $attributes=array_intersect($this->attributes,$attributes);
  185. else
  186. $attributes=$this->attributes;
  187. foreach($attributes as $attribute)
  188. {
  189. if(!$this->skipOnError || !$object->hasErrors($attribute))
  190. $this->validateAttribute($object,$attribute);
  191. }
  192. }
  193. /**
  194. * Returns the JavaScript needed for performing client-side validation.
  195. * Do not override this method if the validator does not support client-side validation.
  196. * Two predefined JavaScript variables can be used:
  197. * <ul>
  198. * <li>value: the value to be validated</li>
  199. * <li>messages: an array used to hold the validation error messages for the value</li>
  200. * </ul>
  201. * @param CModel $object the data object being validated
  202. * @param string $attribute the name of the attribute to be validated.
  203. * @return string the client-side validation script. Null if the validator does not support client-side validation.
  204. * @see CActiveForm::enableClientValidation
  205. * @since 1.1.7
  206. */
  207. public function clientValidateAttribute($object,$attribute)
  208. {
  209. }
  210. /**
  211. * Returns a value indicating whether the validator applies to the specified scenario.
  212. * A validator applies to a scenario as long as any of the following conditions is met:
  213. * <ul>
  214. * <li>the validator's "on" property is empty</li>
  215. * <li>the validator's "on" property contains the specified scenario</li>
  216. * </ul>
  217. * @param string $scenario scenario name
  218. * @return boolean whether the validator applies to the specified scenario.
  219. */
  220. public function applyTo($scenario)
  221. {
  222. if(isset($this->except[$scenario]))
  223. return false;
  224. return empty($this->on) || isset($this->on[$scenario]);
  225. }
  226. /**
  227. * Adds an error about the specified attribute to the active record.
  228. * This is a helper method that performs message selection and internationalization.
  229. * @param CModel $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. protected function addError($object,$attribute,$message,$params=array())
  235. {
  236. $params['{attribute}']=$object->getAttributeLabel($attribute);
  237. $object->addError($attribute,strtr($message,$params));
  238. }
  239. /**
  240. * Checks if the given value is empty.
  241. * A value is considered empty if it is null, an empty array, or the trimmed result is an empty string.
  242. * Note that this method is different from PHP empty(). It will return false when the value is 0.
  243. * @param mixed $value the value to be checked
  244. * @param boolean $trim whether to perform trimming before checking if the string is empty. Defaults to false.
  245. * @return boolean whether the value is empty
  246. */
  247. protected function isEmpty($value,$trim=false)
  248. {
  249. return $value===null || $value===array() || $value==='' || $trim && is_scalar($value) && trim($value)==='';
  250. }
  251. }