PageRenderTime 134ms CodeModel.GetById 127ms app.highlight 4ms RepoModel.GetById 1ms app.codeStats 1ms

/framework/validators/CValidator.php

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