1 | <?php |
||
24 | class NumberValidator extends Validator |
||
25 | { |
||
26 | /** |
||
27 | * @var bool whether the attribute value can only be an integer. Defaults to false. |
||
28 | */ |
||
29 | public $integerOnly = false; |
||
30 | /** |
||
31 | * @var int|float upper limit of the number. Defaults to null, meaning no upper limit. |
||
32 | * @see tooBig for the customized message used when the number is too big. |
||
33 | */ |
||
34 | public $max; |
||
35 | /** |
||
36 | * @var int|float lower limit of the number. Defaults to null, meaning no lower limit. |
||
37 | * @see tooSmall for the customized message used when the number is too small. |
||
38 | */ |
||
39 | public $min; |
||
40 | /** |
||
41 | * @var string user-defined error message used when the value is bigger than [[max]]. |
||
42 | */ |
||
43 | public $tooBig; |
||
44 | /** |
||
45 | * @var string user-defined error message used when the value is smaller than [[min]]. |
||
46 | */ |
||
47 | public $tooSmall; |
||
48 | /** |
||
49 | * @var string the regular expression for matching integers. |
||
50 | */ |
||
51 | public $integerPattern = '/^\s*[+-]?\d+\s*$/'; |
||
52 | /** |
||
53 | * @var string the regular expression for matching numbers. It defaults to a pattern |
||
54 | * that matches floating numbers with optional exponential part (e.g. -1.23e-10). |
||
55 | */ |
||
56 | public $numberPattern = '/^\s*[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\s*$/'; |
||
57 | |||
58 | |||
59 | /** |
||
60 | * @inheritdoc |
||
61 | */ |
||
62 | 20 | public function init() |
|
76 | |||
77 | /** |
||
78 | * @inheritdoc |
||
79 | */ |
||
80 | 5 | public function validateAttribute($model, $attribute) |
|
81 | { |
||
82 | 5 | $value = $model->$attribute; |
|
83 | 5 | if (is_array($value) || (is_object($value) && !method_exists($value, '__toString'))) { |
|
84 | 1 | $this->addError($model, $attribute, $this->message); |
|
85 | 1 | return; |
|
86 | } |
||
87 | 5 | $pattern = $this->integerOnly ? $this->integerPattern : $this->numberPattern; |
|
88 | 5 | if (!preg_match($pattern, "$value")) { |
|
89 | 4 | $this->addError($model, $attribute, $this->message); |
|
90 | 4 | } |
|
91 | 5 | if ($this->min !== null && $value < $this->min) { |
|
92 | 2 | $this->addError($model, $attribute, $this->tooSmall, ['min' => $this->min]); |
|
93 | 2 | } |
|
94 | 5 | if ($this->max !== null && $value > $this->max) { |
|
95 | 1 | $this->addError($model, $attribute, $this->tooBig, ['max' => $this->max]); |
|
96 | 1 | } |
|
97 | 5 | } |
|
98 | |||
99 | /** |
||
100 | * @inheritdoc |
||
101 | */ |
||
102 | 8 | protected function validateValue($value) |
|
118 | |||
119 | /** |
||
120 | * @inheritdoc |
||
121 | */ |
||
122 | 1 | public function clientValidateAttribute($model, $attribute, $view) |
|
129 | |||
130 | /** |
||
131 | * @inheritdoc |
||
132 | */ |
||
133 | 1 | protected function getClientOptions($model, $attribute) |
|
168 | } |
||
169 |