NumberValidator.php 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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\helpers\Json;
  10. use yii\helpers\StringHelper;
  11. use yii\web\JsExpression;
  12. /**
  13. * NumberValidator validates that the attribute value is a number.
  14. *
  15. * The format of the number must match the regular expression specified in [[integerPattern]] or [[numberPattern]].
  16. * Optionally, you may configure the [[max]] and [[min]] properties to ensure the number
  17. * is within certain range.
  18. *
  19. * @author Qiang Xue <qiang.xue@gmail.com>
  20. * @since 2.0
  21. */
  22. class NumberValidator extends Validator
  23. {
  24. /**
  25. * @var bool whether the attribute value can only be an integer. Defaults to false.
  26. */
  27. public $integerOnly = false;
  28. /**
  29. * @var int|float upper limit of the number. Defaults to null, meaning no upper limit.
  30. * @see tooBig for the customized message used when the number is too big.
  31. */
  32. public $max;
  33. /**
  34. * @var int|float lower limit of the number. Defaults to null, meaning no lower limit.
  35. * @see tooSmall for the customized message used when the number is too small.
  36. */
  37. public $min;
  38. /**
  39. * @var string user-defined error message used when the value is bigger than [[max]].
  40. */
  41. public $tooBig;
  42. /**
  43. * @var string user-defined error message used when the value is smaller than [[min]].
  44. */
  45. public $tooSmall;
  46. /**
  47. * @var string the regular expression for matching integers.
  48. */
  49. public $integerPattern = '/^\s*[+-]?\d+\s*$/';
  50. /**
  51. * @var string the regular expression for matching numbers. It defaults to a pattern
  52. * that matches floating numbers with optional exponential part (e.g. -1.23e-10).
  53. */
  54. public $numberPattern = '/^\s*[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\s*$/';
  55. /**
  56. * {@inheritdoc}
  57. */
  58. public function init()
  59. {
  60. parent::init();
  61. if ($this->message === null) {
  62. $this->message = $this->integerOnly ? Yii::t('yii', '{attribute} must be an integer.')
  63. : Yii::t('yii', '{attribute} must be a number.');
  64. }
  65. if ($this->min !== null && $this->tooSmall === null) {
  66. $this->tooSmall = Yii::t('yii', '{attribute} must be no less than {min}.');
  67. }
  68. if ($this->max !== null && $this->tooBig === null) {
  69. $this->tooBig = Yii::t('yii', '{attribute} must be no greater than {max}.');
  70. }
  71. }
  72. /**
  73. * {@inheritdoc}
  74. */
  75. public function validateAttribute($model, $attribute)
  76. {
  77. $value = $model->$attribute;
  78. if ($this->isNotNumber($value)) {
  79. $this->addError($model, $attribute, $this->message);
  80. return;
  81. }
  82. $pattern = $this->integerOnly ? $this->integerPattern : $this->numberPattern;
  83. if (!preg_match($pattern, StringHelper::normalizeNumber($value))) {
  84. $this->addError($model, $attribute, $this->message);
  85. }
  86. if ($this->min !== null && $value < $this->min) {
  87. $this->addError($model, $attribute, $this->tooSmall, ['min' => $this->min]);
  88. }
  89. if ($this->max !== null && $value > $this->max) {
  90. $this->addError($model, $attribute, $this->tooBig, ['max' => $this->max]);
  91. }
  92. }
  93. /**
  94. * {@inheritdoc}
  95. */
  96. protected function validateValue($value)
  97. {
  98. if ($this->isNotNumber($value)) {
  99. return [Yii::t('yii', '{attribute} is invalid.'), []];
  100. }
  101. $pattern = $this->integerOnly ? $this->integerPattern : $this->numberPattern;
  102. if (!preg_match($pattern, StringHelper::normalizeNumber($value))) {
  103. return [$this->message, []];
  104. } elseif ($this->min !== null && $value < $this->min) {
  105. return [$this->tooSmall, ['min' => $this->min]];
  106. } elseif ($this->max !== null && $value > $this->max) {
  107. return [$this->tooBig, ['max' => $this->max]];
  108. }
  109. return null;
  110. }
  111. /*
  112. * @param mixed $value the data value to be checked.
  113. */
  114. private function isNotNumber($value)
  115. {
  116. return is_array($value)
  117. || is_bool($value)
  118. || (is_object($value) && !method_exists($value, '__toString'))
  119. || (!is_object($value) && !is_scalar($value) && $value !== null);
  120. }
  121. /**
  122. * {@inheritdoc}
  123. */
  124. public function clientValidateAttribute($model, $attribute, $view)
  125. {
  126. ValidationAsset::register($view);
  127. $options = $this->getClientOptions($model, $attribute);
  128. return 'yii.validation.number(value, messages, ' . Json::htmlEncode($options) . ');';
  129. }
  130. /**
  131. * {@inheritdoc}
  132. */
  133. public function getClientOptions($model, $attribute)
  134. {
  135. $label = $model->getAttributeLabel($attribute);
  136. $options = [
  137. 'pattern' => new JsExpression($this->integerOnly ? $this->integerPattern : $this->numberPattern),
  138. 'message' => $this->formatMessage($this->message, [
  139. 'attribute' => $label,
  140. ]),
  141. ];
  142. if ($this->min !== null) {
  143. // ensure numeric value to make javascript comparison equal to PHP comparison
  144. // https://github.com/yiisoft/yii2/issues/3118
  145. $options['min'] = is_string($this->min) ? (float) $this->min : $this->min;
  146. $options['tooSmall'] = $this->formatMessage($this->tooSmall, [
  147. 'attribute' => $label,
  148. 'min' => $this->min,
  149. ]);
  150. }
  151. if ($this->max !== null) {
  152. // ensure numeric value to make javascript comparison equal to PHP comparison
  153. // https://github.com/yiisoft/yii2/issues/3118
  154. $options['max'] = is_string($this->max) ? (float) $this->max : $this->max;
  155. $options['tooBig'] = $this->formatMessage($this->tooBig, [
  156. 'attribute' => $label,
  157. 'max' => $this->max,
  158. ]);
  159. }
  160. if ($this->skipOnEmpty) {
  161. $options['skipOnEmpty'] = 1;
  162. }
  163. return $options;
  164. }
  165. }