summaryrefslogtreecommitdiff
path: root/framework/validators/CInlineValidator.php
blob: f88350d5dced0ca96c8deb59e1522dd217c0f294 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
/**
 * CInlineValidator class file.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @link http://www.yiiframework.com/
 * @copyright Copyright &copy; 2008-2011 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

/**
 * CInlineValidator represents a validator which is defined as a method in the object being validated.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @version $Id: CInlineValidator.php 3517 2011-12-28 23:22:21Z mdomba $
 * @package system.validators
 * @since 1.0
 */
class CInlineValidator extends CValidator
{
	/**
	 * @var string the name of the validation method defined in the active record class
	 */
	public $method;
	/**
	 * @var array additional parameters that are passed to the validation method
	 */
	public $params;
	/**
	 * @var string the name of the method that returns the client validation code (See {@link clientValidateAttribute}).
	 */
	public $clientValidate;

	/**
	 * Validates the attribute of the object.
	 * If there is any error, the error message is added to the object.
	 * @param CModel $object the object being validated
	 * @param string $attribute the attribute being validated
	 */
	protected function validateAttribute($object,$attribute)
	{
		$method=$this->method;
		$object->$method($attribute,$this->params);
	}

	/**
	 * Returns the JavaScript code needed to perform client-side validation by calling the {@link clientValidate} method.
	 * In the client validation code, these variables are predefined:
	 * <ul>
	 * <li>value: the current input value associated with this attribute.</li>
	 * <li>messages: an array that may be appended with new error messages for the attribute.</li>
	 * <li>attribute: a data structure keeping all client-side options for the attribute</li>
	 * </ul>
	 * <b>Example</b>:
	 *
	 * If {@link clientValidate} is set to "clientValidate123", clientValidate123() is the name of
	 * the method that returns the client validation code and can look like:
	 * <pre>
	 * <?php
	 *   public function clientValidate123($attribute)
	 *   {
	 *      $js = "if(value != '123') { messages.push('Value should be 123'); }";
	 *      return $js;
	 *   }
	 * ?>
	 * </pre>
	 * @param CModel $object the data object being validated
	 * @param string $attribute the name of the attribute to be validated.
	 * @return string the client-side validation script.
	 * @see CActiveForm::enableClientValidation
	 * @since 1.1.9
	 */
	public function clientValidateAttribute($object,$attribute)
	{
		if($this->clientValidate!==null)
		{
			$method=$this->clientValidate;
			return $object->$method($attribute);
		}
	}
}