Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

160 linhas
5.6KB

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