CompareValidator.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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. case '===':
  103. $this->message = Yii::t('yii', '{attribute} must be equal to "{compareValueOrAttribute}".');
  104. break;
  105. case '!=':
  106. case '!==':
  107. $this->message = Yii::t('yii', '{attribute} must not be equal to "{compareValueOrAttribute}".');
  108. break;
  109. case '>':
  110. $this->message = Yii::t('yii', '{attribute} must be greater than "{compareValueOrAttribute}".');
  111. break;
  112. case '>=':
  113. $this->message = Yii::t('yii', '{attribute} must be greater than or equal to "{compareValueOrAttribute}".');
  114. break;
  115. case '<':
  116. $this->message = Yii::t('yii', '{attribute} must be less than "{compareValueOrAttribute}".');
  117. break;
  118. case '<=':
  119. $this->message = Yii::t('yii', '{attribute} must be less than or equal to "{compareValueOrAttribute}".');
  120. break;
  121. default:
  122. throw new InvalidConfigException("Unknown operator: {$this->operator}");
  123. }
  124. }
  125. }
  126. /**
  127. * {@inheritdoc}
  128. */
  129. public function validateAttribute($model, $attribute)
  130. {
  131. $value = $model->$attribute;
  132. if (is_array($value)) {
  133. $this->addError($model, $attribute, Yii::t('yii', '{attribute} is invalid.'));
  134. return;
  135. }
  136. if ($this->compareValue !== null) {
  137. if ($this->compareValue instanceof \Closure) {
  138. $this->compareValue = call_user_func($this->compareValue);
  139. }
  140. $compareLabel = $compareValue = $compareValueOrAttribute = $this->compareValue;
  141. } else {
  142. $compareAttribute = $this->compareAttribute === null ? $attribute . '_repeat' : $this->compareAttribute;
  143. $compareValue = $model->$compareAttribute;
  144. $compareLabel = $compareValueOrAttribute = $model->getAttributeLabel($compareAttribute);
  145. }
  146. if (!$this->compareValues($this->operator, $this->type, $value, $compareValue)) {
  147. $this->addError($model, $attribute, $this->message, [
  148. 'compareAttribute' => $compareLabel,
  149. 'compareValue' => $compareValue,
  150. 'compareValueOrAttribute' => $compareValueOrAttribute,
  151. ]);
  152. }
  153. }
  154. /**
  155. * {@inheritdoc}
  156. */
  157. protected function validateValue($value)
  158. {
  159. if ($this->compareValue === null) {
  160. throw new InvalidConfigException('CompareValidator::compareValue must be set.');
  161. }
  162. if ($this->compareValue instanceof \Closure) {
  163. $this->compareValue = call_user_func($this->compareValue);
  164. }
  165. if (!$this->compareValues($this->operator, $this->type, $value, $this->compareValue)) {
  166. return [$this->message, [
  167. 'compareAttribute' => $this->compareValue,
  168. 'compareValue' => $this->compareValue,
  169. 'compareValueOrAttribute' => $this->compareValue,
  170. ]];
  171. }
  172. return null;
  173. }
  174. /**
  175. * Compares two values with the specified operator.
  176. * @param string $operator the comparison operator
  177. * @param string $type the type of the values being compared
  178. * @param mixed $value the value being compared
  179. * @param mixed $compareValue another value being compared
  180. * @return bool whether the comparison using the specified operator is true.
  181. */
  182. protected function compareValues($operator, $type, $value, $compareValue)
  183. {
  184. if ($type === self::TYPE_NUMBER) {
  185. $value = (float) $value;
  186. $compareValue = (float) $compareValue;
  187. } else {
  188. $value = (string) $value;
  189. $compareValue = (string) $compareValue;
  190. }
  191. switch ($operator) {
  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. case '<=':
  207. return $value <= $compareValue;
  208. default:
  209. return false;
  210. }
  211. }
  212. /**
  213. * {@inheritdoc}
  214. */
  215. public function clientValidateAttribute($model, $attribute, $view)
  216. {
  217. if ($this->compareValue != null && $this->compareValue instanceof \Closure) {
  218. $this->compareValue = call_user_func($this->compareValue);
  219. }
  220. ValidationAsset::register($view);
  221. $options = $this->getClientOptions($model, $attribute);
  222. return 'yii.validation.compare(value, messages, ' . json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ', $form);';
  223. }
  224. /**
  225. * {@inheritdoc}
  226. */
  227. public function getClientOptions($model, $attribute)
  228. {
  229. $options = [
  230. 'operator' => $this->operator,
  231. 'type' => $this->type,
  232. ];
  233. if ($this->compareValue !== null) {
  234. $options['compareValue'] = $this->compareValue;
  235. $compareLabel = $compareValue = $compareValueOrAttribute = $this->compareValue;
  236. } else {
  237. $compareAttribute = $this->compareAttribute === null ? $attribute . '_repeat' : $this->compareAttribute;
  238. $compareValue = $model->getAttributeLabel($compareAttribute);
  239. $options['compareAttribute'] = Html::getInputId($model, $compareAttribute);
  240. $options['compareAttributeName'] = Html::getInputName($model, $compareAttribute);
  241. $compareLabel = $compareValueOrAttribute = $model->getAttributeLabel($compareAttribute);
  242. }
  243. if ($this->skipOnEmpty) {
  244. $options['skipOnEmpty'] = 1;
  245. }
  246. $options['message'] = $this->formatMessage($this->message, [
  247. 'attribute' => $model->getAttributeLabel($attribute),
  248. 'compareAttribute' => $compareLabel,
  249. 'compareValue' => $compareValue,
  250. 'compareValueOrAttribute' => $compareValueOrAttribute,
  251. ]);
  252. return $options;
  253. }
  254. }