-
-
Notifications
You must be signed in to change notification settings - Fork 6.9k
/
NumberValidator.php
211 lines (193 loc) · 6.96 KB
/
NumberValidator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
namespace yii\validators;
use Yii;
use yii\helpers\Json;
use yii\helpers\StringHelper;
use yii\web\JsExpression;
/**
* NumberValidator validates that the attribute value is a number.
*
* The format of the number must match the regular expression specified in [[integerPattern]] or [[numberPattern]].
* Optionally, you may configure the [[max]] and [[min]] properties to ensure the number
* is within certain range.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class NumberValidator extends Validator
{
/**
* @var bool whether to allow array type attribute. Defaults to false.
* @since 2.0.42
*/
public $allowArray = false;
/**
* @var bool whether the attribute value can only be an integer. Defaults to false.
*/
public $integerOnly = false;
/**
* @var int|float|null upper limit of the number. Defaults to null, meaning no upper limit.
* @see tooBig for the customized message used when the number is too big.
*/
public $max;
/**
* @var int|float|null lower limit of the number. Defaults to null, meaning no lower limit.
* @see tooSmall for the customized message used when the number is too small.
*/
public $min;
/**
* @var string user-defined error message used when the value is bigger than [[max]].
*/
public $tooBig;
/**
* @var string user-defined error message used when the value is smaller than [[min]].
*/
public $tooSmall;
/**
* @var string the regular expression for matching integers.
*/
public $integerPattern = '/^[+-]?\d+$/';
/**
* @var string the regular expression for matching numbers. It defaults to a pattern
* that matches floating numbers with optional exponential part (e.g. -1.23e-10).
*/
public $numberPattern = '/^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$/';
/**
* {@inheritdoc}
*/
public function init()
{
parent::init();
if ($this->message === null) {
$this->message = $this->integerOnly ? Yii::t('yii', '{attribute} must be an integer.')
: Yii::t('yii', '{attribute} must be a number.');
}
if ($this->min !== null && $this->tooSmall === null) {
$this->tooSmall = Yii::t('yii', '{attribute} must be no less than {min}.');
}
if ($this->max !== null && $this->tooBig === null) {
$this->tooBig = Yii::t('yii', '{attribute} must be no greater than {max}.');
}
}
/**
* {@inheritdoc}
*/
public function validateAttribute($model, $attribute)
{
$value = $model->$attribute;
if (is_array($value) && !$this->allowArray) {
$this->addError($model, $attribute, $this->message);
return;
}
$values = !is_array($value) ? [$value] : $value;
foreach ($values as $value) {
if ($this->isNotNumber($value)) {
$this->addError($model, $attribute, $this->message);
return;
}
$pattern = $this->integerOnly ? $this->integerPattern : $this->numberPattern;
if (!preg_match($pattern, StringHelper::normalizeNumber($value))) {
$this->addError($model, $attribute, $this->message);
}
if ($this->min !== null && $value < $this->min) {
$this->addError($model, $attribute, $this->tooSmall, ['min' => $this->min]);
}
if ($this->max !== null && $value > $this->max) {
$this->addError($model, $attribute, $this->tooBig, ['max' => $this->max]);
}
}
}
/**
* {@inheritdoc}
*/
protected function validateValue($value)
{
if (is_array($value) && !$this->allowArray) {
return [Yii::t('yii', '{attribute} is invalid.'), []];
}
$values = !is_array($value) ? [$value] : $value;
foreach ($values as $value) {
if ($this->isNotNumber($value)) {
return [Yii::t('yii', '{attribute} is invalid.'), []];
}
$pattern = $this->integerOnly ? $this->integerPattern : $this->numberPattern;
if (!preg_match($pattern, StringHelper::normalizeNumber($value))) {
return [$this->message, []];
} elseif ($this->min !== null && $value < $this->min) {
return [$this->tooSmall, ['min' => $this->min]];
} elseif ($this->max !== null && $value > $this->max) {
return [$this->tooBig, ['max' => $this->max]];
}
}
return null;
}
/**
* @param mixed $value the data value to be checked.
*/
private function isNotNumber($value)
{
return is_array($value)
|| is_bool($value)
|| (is_object($value) && !method_exists($value, '__toString'))
|| (!is_object($value) && !is_scalar($value) && $value !== null);
}
/**
* {@inheritdoc}
*/
public function clientValidateAttribute($model, $attribute, $view)
{
ValidationAsset::register($view);
$options = $this->getClientOptions($model, $attribute);
return 'yii.validation.number(value, messages, ' . Json::htmlEncode($options) . ');';
}
/**
* {@inheritdoc}
*/
public function getClientOptions($model, $attribute)
{
$label = $model->getAttributeLabel($attribute);
$options = [
'pattern' => new JsExpression($this->integerOnly ? $this->integerPattern : $this->numberPattern),
'message' => $this->formatMessage($this->message, [
'attribute' => $label,
]),
];
if ($this->min !== null) {
// ensure numeric value to make javascript comparison equal to PHP comparison
// https://github.com/yiisoft/yii2/issues/3118
$options['min'] = is_string($this->min) ? (float) $this->min : $this->min;
$options['tooSmall'] = $this->formatMessage($this->tooSmall, [
'attribute' => $label,
'min' => $this->min,
]);
}
if ($this->max !== null) {
// ensure numeric value to make javascript comparison equal to PHP comparison
// https://github.com/yiisoft/yii2/issues/3118
$options['max'] = is_string($this->max) ? (float) $this->max : $this->max;
$options['tooBig'] = $this->formatMessage($this->tooBig, [
'attribute' => $label,
'max' => $this->max,
]);
}
if ($this->skipOnEmpty) {
$options['skipOnEmpty'] = 1;
}
return $options;
}
/**
* {@inheritdoc}
*/
public function isEmpty($value)
{
if ($this->isEmpty !== null) {
return call_user_func($this->isEmpty, $value);
}
return $value === null || $value === '';
}
}