CommaNumberValidator.php 1.69 KB
<?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 );
    }
}