CompareValidator.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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\InvalidConfigException;
  10. use yii\helpers\Html;
  11. /**
  12. * CompareValidator compares the specified attribute value with another value.
  13. *
  14. * The value being compared with can be another attribute value
  15. * (specified via [[compareAttribute]]) or a constant (specified via
  16. * [[compareValue]]. When both are specified, the latter takes
  17. * precedence. If neither is specified, the attribute will be compared
  18. * with another attribute whose name is by appending "_repeat" to the source
  19. * attribute name.
  20. *
  21. * CompareValidator supports different comparison operators, specified
  22. * via the [[operator]] property.
  23. *
  24. * The default comparison function is based on string values, which means the values
  25. * are compared byte by byte. When comparing numbers, make sure to set the [[$type]]
  26. * to [[TYPE_NUMBER]] to enable numeric comparison.
  27. *
  28. * @author Qiang Xue <qiang.xue@gmail.com>
  29. * @since 2.0
  30. */
  31. class CompareValidator extends Validator
  32. {
  33. /**
  34. * Constant for specifying the comparison [[type]] by numeric values.
  35. * @since 2.0.11
  36. * @see type
  37. */
  38. const TYPE_STRING = 'string';
  39. /**
  40. * Constant for specifying the comparison [[type]] by numeric values.
  41. * @since 2.0.11
  42. * @see type
  43. */
  44. const TYPE_NUMBER = 'number';
  45. /**
  46. * @var string the name of the attribute to be compared with. When both this property
  47. * and [[compareValue]] are set, the latter takes precedence. If neither is set,
  48. * it assumes the comparison is against another attribute whose name is formed by
  49. * appending '_repeat' to the attribute being validated. For example, if 'password' is
  50. * being validated, then the attribute to be compared would be 'password_repeat'.
  51. * @see compareValue
  52. */
  53. public $compareAttribute;
  54. /**
  55. * @var mixed the constant value to be compared with. When both this property
  56. * and [[compareAttribute]] are set, this property takes precedence.
  57. * @see compareAttribute
  58. */
  59. public $compareValue;
  60. /**
  61. * @var string the type of the values being compared. The follow types are supported:
  62. *
  63. * - [[TYPE_STRING|string]]: the values are being compared as strings. No conversion will be done before comparison.
  64. * - [[TYPE_NUMBER|number]]: the values are being compared as numbers. String values will be converted into numbers before comparison.
  65. */
  66. public $type = self::TYPE_STRING;
  67. /**
  68. * @var string the operator for comparison. The following operators are supported:
  69. *
  70. * - `==`: check if two values are equal. The comparison is done is non-strict mode.
  71. * - `===`: check if two values are equal. The comparison is done is strict mode.
  72. * - `!=`: check if two values are NOT equal. The comparison is done is non-strict mode.
  73. * - `!==`: check if two values are NOT equal. The comparison is done is strict mode.
  74. * - `>`: check if value being validated is greater than the value being compared with.
  75. * - `>=`: check if value being validated is greater than or equal to the value being compared with.
  76. * - `<`: check if value being validated is less than the value being compared with.
  77. * - `<=`: check if value being validated is less than or equal to the value being compared with.
  78. *
  79. * When you want to compare numbers, make sure to also set [[type]] to `number`.
  80. */
  81. public $operator = '==';
  82. /**
  83. * @var string the user-defined error message. It may contain the following placeholders which
  84. * will be replaced accordingly by the validator:
  85. *
  86. * - `{attribute}`: the label of the attribute being validated
  87. * - `{value}`: the value of the attribute being validated
  88. * - `{compareValue}`: the value or the attribute label to be compared with
  89. * - `{compareAttribute}`: the label of the attribute to be compared with
  90. * - `{compareValueOrAttribute}`: the value or the attribute label to be compared with
  91. */
  92. public $message;
  93. /**
  94. * {@inheritdoc}
  95. */
  96. public function init()
  97. {
  98. parent::init();
  99. if ($this->message === null) {
  100. switch ($this->operator) {
  101. case '==':
  102. $this->message = Yii::t('yii', '{attribute} must be equal to "{compareValueOrAttribute}".');
  103. break;
  104. case '===':
  105. $this->message = Yii::t('yii', '{attribute} must be equal to "{compareValueOrAttribute}".');
  106. break;
  107. case '!=':
  108. $this->message = Yii::t('yii', '{attribute} must not be equal to "{compareValueOrAttribute}".');
  109. break;
  110. case '!==':
  111. $this->message = Yii::t('yii', '{attribute} must not be equal to "{compareValueOrAttribute}".');
  112. break;
  113. case '>':
  114. $this->message = Yii::t('yii', '{attribute} must be greater than "{compareValueOrAttribute}".');
  115. break;
  116. case '>=':
  117. $this->message = Yii::t('yii', '{attribute} must be greater than or equal to "{compareValueOrAttribute}".');
  118. break;
  119. case '<':
  120. $this->message = Yii::t('yii', '{attribute} must be less than "{compareValueOrAttribute}".');
  121. break;
  122. case '<=':
  123. $this->message = Yii::t('yii', '{attribute} must be less than or equal to "{compareValueOrAttribute}".');
  124. break;
  125. default:
  126. throw new InvalidConfigException("Unknown operator: {$this->operator}");
  127. }
  128. }
  129. }
  130. /**
  131. * {@inheritdoc}
  132. */
  133. public function validateAttribute($model, $attribute)
  134. {
  135. $value = $model->$attribute;
  136. if (is_array($value)) {
  137. $this->addError($model, $attribute, Yii::t('yii', '{attribute} is invalid.'));
  138. return;
  139. }
  140. if ($this->compareValue !== null) {
  141. $compareLabel = $compareValue = $compareValueOrAttribute = $this->compareValue;
  142. } else {
  143. $compareAttribute = $this->compareAttribute === null ? $attribute . '_repeat' : $this->compareAttribute;
  144. $compareValue = $model->$compareAttribute;
  145. $compareLabel = $compareValueOrAttribute = $model->getAttributeLabel($compareAttribute);
  146. }
  147. if (!$this->compareValues($this->operator, $this->type, $value, $compareValue)) {
  148. $this->addError($model, $attribute, $this->message, [
  149. 'compareAttribute' => $compareLabel,
  150. 'compareValue' => $compareValue,
  151. 'compareValueOrAttribute' => $compareValueOrAttribute,
  152. ]);
  153. }
  154. }
  155. /**
  156. * {@inheritdoc}
  157. */
  158. protected function validateValue($value)
  159. {
  160. if ($this->compareValue === null) {
  161. throw new InvalidConfigException('CompareValidator::compareValue must be set.');
  162. }
  163. if (!$this->compareValues($this->operator, $this->type, $value, $this->compareValue)) {
  164. return [$this->message, [
  165. 'compareAttribute' => $this->compareValue,
  166. 'compareValue' => $this->compareValue,
  167. 'compareValueOrAttribute' => $this->compareValue,
  168. ]];
  169. }
  170. return null;
  171. }
  172. /**
  173. * Compares two values with the specified operator.
  174. * @param string $operator the comparison operator
  175. * @param string $type the type of the values being compared
  176. * @param mixed $value the value being compared
  177. * @param mixed $compareValue another value being compared
  178. * @return bool whether the comparison using the specified operator is true.
  179. */
  180. protected function compareValues($operator, $type, $value, $compareValue)
  181. {
  182. if ($type === self::TYPE_NUMBER) {
  183. $value = (float) $value;
  184. $compareValue = (float) $compareValue;
  185. } else {
  186. $value = (string) $value;
  187. $compareValue = (string) $compareValue;
  188. }
  189. switch ($operator) {
  190. case '==':
  191. return $value == $compareValue;
  192. case '===':
  193. return $value === $compareValue;
  194. case '!=':
  195. return $value != $compareValue;
  196. case '!==':
  197. return $value !== $compareValue;
  198. case '>':
  199. return $value > $compareValue;
  200. case '>=':
  201. return $value >= $compareValue;
  202. case '<':
  203. return $value < $compareValue;
  204. case '<=':
  205. return $value <= $compareValue;
  206. default:
  207. return false;
  208. }
  209. }
  210. /**
  211. * {@inheritdoc}
  212. */
  213. public function clientValidateAttribute($model, $attribute, $view)
  214. {
  215. ValidationAsset::register($view);
  216. $options = $this->getClientOptions($model, $attribute);
  217. return 'yii.validation.compare(value, messages, ' . json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ', $form);';
  218. }
  219. /**
  220. * {@inheritdoc}
  221. */
  222. public function getClientOptions($model, $attribute)
  223. {
  224. $options = [
  225. 'operator' => $this->operator,
  226. 'type' => $this->type,
  227. ];
  228. if ($this->compareValue !== null) {
  229. $options['compareValue'] = $this->compareValue;
  230. $compareLabel = $compareValue = $compareValueOrAttribute = $this->compareValue;
  231. } else {
  232. $compareAttribute = $this->compareAttribute === null ? $attribute . '_repeat' : $this->compareAttribute;
  233. $compareValue = $model->getAttributeLabel($compareAttribute);
  234. $options['compareAttribute'] = Html::getInputId($model, $compareAttribute);
  235. $options['compareAttributeName'] = Html::getInputName($model, $compareAttribute);
  236. $compareLabel = $compareValueOrAttribute = $model->getAttributeLabel($compareAttribute);
  237. }
  238. if ($this->skipOnEmpty) {
  239. $options['skipOnEmpty'] = 1;
  240. }
  241. $options['message'] = $this->formatMessage($this->message, [
  242. 'attribute' => $model->getAttributeLabel($attribute),
  243. 'compareAttribute' => $compareLabel,
  244. 'compareValue' => $compareValue,
  245. 'compareValueOrAttribute' => $compareValueOrAttribute,
  246. ]);
  247. return $options;
  248. }
  249. }