From 9f08218160d2c16c5bfb33ed1a5507cd20194e97 Mon Sep 17 00:00:00 2001 From: Mihail Date: Wed, 25 Nov 2015 14:56:05 +0200 Subject: [PATCH] add comma number validator --- common/components/CommaNumberValidator.php | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ common/models/Currency.php | 7 ++++--- 2 files changed, 65 insertions(+), 3 deletions(-) create mode 100644 common/components/CommaNumberValidator.php diff --git a/common/components/CommaNumberValidator.php b/common/components/CommaNumberValidator.php new file mode 100644 index 0000000..4a871bd --- /dev/null +++ b/common/components/CommaNumberValidator.php @@ -0,0 +1,61 @@ +$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 ); + } +} \ No newline at end of file diff --git a/common/models/Currency.php b/common/models/Currency.php index 555f3f5..e177145 100755 --- a/common/models/Currency.php +++ b/common/models/Currency.php @@ -30,9 +30,10 @@ class Currency extends \yii\db\ActiveRecord { return [ [['name', 'rate'], 'required'], - [['rate'], 'filter','filter' => function($value){ - return (float) str_replace( ',', '.', $value );} - ], +// [['rate'], 'filter','filter' => function($value){ +// return (float) str_replace( ',', '.', $value );} +// ], + ['rate', \common\components\CommaNumberValidator::className()], [['is_default'], 'integer'], [['timestamp'], 'safe'], [['name'], 'string', 'max' => 50], -- libgit2 0.21.4