CommaNumberValidator.php
1.69 KB
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
<?php
/**
* Created by PhpStorm.
* User: Tsurkanov
* Date: 25.11.2015
* Time: 13:51
*/
namespace common\components;
use yii\validators\NumberValidator;
/**
* Class CommaNumberValidator
* @package common\components
* validator identic to NumberValidator,
* with one change - comma replaced to dot,
* thus values such 21,4; 45,05 - will be valid
*/
class CommaNumberValidator extends NumberValidator {
// override parent pattern - add ',' to it
public $numberPattern = '/^\s*[-+]?[0-9]*[\.,]?[0-9]+([eE][-+]?[0-9]+)?\s*$/';
public function validateAttribute($model, $attribute)
{
$value = $model->$attribute;
if ( !is_array($value) ) {
$model->$attribute = $this->commaReplacement( $value );
$value = $model->$attribute;
}
if (is_array($value)) {
$this->addError($model, $attribute, $this->message);
return;
}
$pattern = $this->integerOnly ? $this->integerPattern : $this->numberPattern;
if (!preg_match($pattern, "$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]);
}
}
protected function validateValue($value)
{
$value = $this->commaReplacement( $value );
return parent::validateValue( $value );
}
protected function commaReplacement( $value )
{
return str_replace( ',', '.', $value );
}
}