CompareValidator.php 7.85 KB
Newer Older
w  
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
w  
Qiang Xue committed
5 6 7
 * @license http://www.yiiframework.com/license/
 */

w  
Qiang Xue committed
8
namespace yii\validators;
Qiang Xue committed
9

Qiang Xue committed
10 11
use Yii;
use yii\base\InvalidConfigException;
12
use yii\helpers\Html;
w  
Qiang Xue committed
13

w  
Qiang Xue committed
14
/**
w  
Qiang Xue committed
15
 * CompareValidator compares the specified attribute value with another value and validates if they are equal.
w  
Qiang Xue committed
16 17
 *
 * The value being compared with can be another attribute value
w  
Qiang Xue committed
18 19
 * (specified via [[compareAttribute]]) or a constant (specified via
 * [[compareValue]]. When both are specified, the latter takes
w  
Qiang Xue committed
20 21 22 23
 * precedence. If neither is specified, the attribute will be compared
 * with another attribute whose name is by appending "_repeat" to the source
 * attribute name.
 *
w  
Qiang Xue committed
24
 * The comparison can be either [[strict]] or not.
w  
Qiang Xue committed
25
 *
w  
Qiang Xue committed
26 27
 * CompareValidator supports different comparison operators, specified
 * via the [[operator]] property.
w  
Qiang Xue committed
28 29
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
w  
Qiang Xue committed
30
 * @since 2.0
w  
Qiang Xue committed
31
 */
w  
Qiang Xue committed
32
class CompareValidator extends Validator
w  
Qiang Xue committed
33 34
{
	/**
Qiang Xue committed
35 36 37 38 39 40
	 * @var string the name of the attribute to be compared with. When both this property
	 * and [[compareValue]] are set, the latter takes precedence. If neither is set,
	 * it assumes the comparison is against another attribute whose name is formed by
	 * appending '_repeat' to the attribute being validated. For example, if 'password' is
	 * being validated, then the attribute to be compared would be 'password_repeat'.
	 * @see compareValue
w  
Qiang Xue committed
41 42 43
	 */
	public $compareAttribute;
	/**
Qiang Xue committed
44 45 46
	 * @var string the constant value to be compared with. When both this property
	 * and [[compareAttribute]] are set, this property takes precedence.
	 * @see compareAttribute
w  
Qiang Xue committed
47 48 49
	 */
	public $compareValue;
	/**
Qiang Xue committed
50 51 52 53 54 55
	 * @var string the operator for comparison. The following operators are supported:
	 *
	 * - '==': validates to see if the two values are equal. The comparison is done is non-strict mode.
	 * - '===': validates to see if the two values are equal. The comparison is done is strict mode.
	 * - '!=': validates to see if the two values are NOT equal. The comparison is done is non-strict mode.
	 * - '!==': validates to see if the two values are NOT equal. The comparison is done is strict mode.
Qiang Xue committed
56 57 58 59
	 * - `>`: validates to see if the value being validated is greater than the value being compared with.
	 * - `>=`: validates to see if the value being validated is greater than or equal to the value being compared with.
	 * - `<`: validates to see if the value being validated is less than the value being compared with.
	 * - `<=`: validates to see if the value being validated is less than or equal to the value being compared with.
w  
Qiang Xue committed
60
	 */
gsd committed
61
	public $operator = '==';
62 63 64 65 66 67 68 69 70
	/**
	 * @var string the user-defined error message. It may contain the following placeholders which
	 * will be replaced accordingly by the validator:
	 *
	 * - `{attribute}`: the label of the attribute being validated
	 * - `{value}`: the value of the attribute being validated
	 * - `{compareValue}`: the value or the attribute label to be compared with
	 */
	public $message;
w  
Qiang Xue committed
71

Qiang Xue committed
72 73 74 75 76 77 78 79 80 81

	/**
	 * Initializes the validator.
	 */
	public function init()
	{
		parent::init();
		if ($this->message === null) {
			switch ($this->operator) {
				case '==':
82
					$this->message = Yii::t('yii', '{attribute} must be repeated exactly.');
Qiang Xue committed
83 84
					break;
				case '===':
85
					$this->message = Yii::t('yii', '{attribute} must be repeated exactly.');
Qiang Xue committed
86 87
					break;
				case '!=':
88
					$this->message = Yii::t('yii', '{attribute} must not be equal to "{compareValue}".');
Qiang Xue committed
89 90
					break;
				case '!==':
91
					$this->message = Yii::t('yii', '{attribute} must not be equal to "{compareValue}".');
Qiang Xue committed
92 93
					break;
				case '>':
94
					$this->message = Yii::t('yii', '{attribute} must be greater than "{compareValue}".');
Qiang Xue committed
95 96
					break;
				case '>=':
97
					$this->message = Yii::t('yii', '{attribute} must be greater than or equal to "{compareValue}".');
Qiang Xue committed
98 99
					break;
				case '<':
100
					$this->message = Yii::t('yii', '{attribute} must be less than "{compareValue}".');
Qiang Xue committed
101 102
					break;
				case '<=':
103
					$this->message = Yii::t('yii', '{attribute} must be less than or equal to "{compareValue}".');
Qiang Xue committed
104 105 106 107 108 109 110
					break;
				default:
					throw new InvalidConfigException("Unknown operator: {$this->operator}");
			}
		}
	}

w  
Qiang Xue committed
111 112 113
	/**
	 * Validates the attribute of the object.
	 * If there is any error, the error message is added to the object.
w  
Qiang Xue committed
114
	 * @param \yii\base\Model $object the object being validated
w  
Qiang Xue committed
115
	 * @param string $attribute the attribute being validated
Qiang Xue committed
116
	 * @throws InvalidConfigException if CompareValidator::operator is invalid
w  
Qiang Xue committed
117
	 */
w  
Qiang Xue committed
118
	public function validateAttribute($object, $attribute)
w  
Qiang Xue committed
119 120
	{
		$value = $object->$attribute;
Qiang Xue committed
121
		if (is_array($value)) {
122
			$this->addError($object, $attribute, Yii::t('yii', '{attribute} is invalid.'));
Qiang Xue committed
123 124
			return;
		}
w  
Qiang Xue committed
125
		if ($this->compareValue !== null) {
Qiang Xue committed
126
			$compareLabel = $compareValue = $this->compareValue;
Qiang Xue committed
127
		} else {
Qiang Xue committed
128
			$compareAttribute = $this->compareAttribute === null ? $attribute . '_repeat' : $this->compareAttribute;
w  
Qiang Xue committed
129
			$compareValue = $object->$compareAttribute;
Qiang Xue committed
130
			$compareLabel = $object->getAttributeLabel($compareAttribute);
w  
Qiang Xue committed
131 132
		}

w  
Qiang Xue committed
133
		switch ($this->operator) {
Qiang Xue committed
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
			case '==': $valid = $value == $compareValue; break;
			case '===': $valid = $value === $compareValue; break;
			case '!=': $valid = $value != $compareValue; break;
			case '!==': $valid = $value !== $compareValue; break;
			case '>': $valid = $value > $compareValue; break;
			case '>=': $valid = $value >= $compareValue; break;
			case '<': $valid = $value < $compareValue; break;
			case '<=': $valid = $value <= $compareValue; break;
			default: $valid = false; break;
		}
		if (!$valid) {
			$this->addError($object, $attribute, $this->message, array(
				'{compareAttribute}' => $compareLabel,
				'{compareValue}' => $compareValue,
			));
w  
Qiang Xue committed
149 150 151
		}
	}

Qiang Xue committed
152 153 154 155
	/**
	 * Validates the given value.
	 * @param mixed $value the value to be validated.
	 * @return boolean whether the value is valid.
Qiang Xue committed
156
	 * @throws InvalidConfigException if [[compareValue]] is not set.
Qiang Xue committed
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
	 */
	public function validateValue($value)
	{
		if ($this->compareValue === null) {
			throw new InvalidConfigException('CompareValidator::compareValue must be set.');
		}

		switch ($this->operator) {
			case '==': return $value == $this->compareValue;
			case '===': return $value === $this->compareValue;
			case '!=': return $value != $this->compareValue;
			case '!==': return $value !== $this->compareValue;
			case '>': return $value > $this->compareValue;
			case '>=': return $value >= $this->compareValue;
			case '<': return $value < $this->compareValue;
			case '<=': return $value <= $this->compareValue;
		}
	}

w  
Qiang Xue committed
176 177
	/**
	 * Returns the JavaScript needed for performing client-side validation.
w  
Qiang Xue committed
178
	 * @param \yii\base\Model $object the data object being validated
Alexander Makarov committed
179 180
	 * @param string $attribute the name of the attribute to be validated
	 * @return string the client-side validation script
181 182
	 * @param \yii\base\View $view the view object that is going to be used to render views or view files
	 * containing a model form with this validator applied.
Qiang Xue committed
183
	 * @throws InvalidConfigException if CompareValidator::operator is invalid
w  
Qiang Xue committed
184
	 */
185
	public function clientValidateAttribute($object, $attribute, $view)
w  
Qiang Xue committed
186
	{
187 188
		$options = array('operator' => $this->operator);

w  
Qiang Xue committed
189
		if ($this->compareValue !== null) {
190 191
			$options['compareValue'] = $this->compareValue;
			$compareValue = $this->compareValue;
Qiang Xue committed
192
		} else {
Qiang Xue committed
193
			$compareAttribute = $this->compareAttribute === null ? $attribute . '_repeat' : $this->compareAttribute;
194 195
			$compareValue = $object->getAttributeLabel($compareAttribute);
			$options['compareAttribute'] = Html::getInputId($object, $compareAttribute);
w  
Qiang Xue committed
196
		}
197 198 199 200 201

		if ($this->skipOnEmpty) {
			$options['skipOnEmpty'] = 1;
		}

202
		$options['message'] = Html::encode(strtr($this->message, array(
w  
Qiang Xue committed
203
			'{attribute}' => $object->getAttributeLabel($attribute),
204 205 206
			'{value}' => $object->$attribute,
			'{compareValue}' => $compareValue,
		)));
w  
Qiang Xue committed
207

208
		ValidationAsset::register($view);
209
		return 'yii.validation.compare(value, messages, ' . json_encode($options) . ');';
w  
Qiang Xue committed
210 211
	}
}