How can I correct this validation?

There is a field for price in my form that will be saved in a double format into db. In the controller I get a float number and replace ‘,’ with ‘.’ and I add one validation rule that check user balance with $_POST[‘model’][‘money’].

it’s my code:

It’s great worked but if I post float number with ‘,’ that more than user balance I get error: it’s not number but I must get error from money function.

for example:

balance = 5

$_POST[‘money’] = 6.5 and I get error from money function and it’s true.

but if I post

$_POST[‘money’] = 6,5 I get error from numerical and not money function.

Why? Do validation work in money()? because before validate() in controller I replaced ‘,’ with ‘.’.

controler:


$model=new Model;

$model->scenario = 'money';

$model->attributes = $_POST['Model'];

$model->sum = str_replace(",", ".", $_POST['Model']['money']));

if($model->validate()){

	

}

model:


return array(

	array('money','numerical', 'integerOnly'=>false,'allowEmpty'=>false,'skipOnError'=>true,'on'=>'money'),

	array('money','compare','compareValue'=>0,'operator'=>'>','skipOnError'=>true,'on'=>'money'),

	array('money','money','on'=>'money','skipOnError'=>true),

);


public function money($attribute,$params){

	if(!$this->hasErrors()){

		$user = User::model()->findByPk(Yii::app()->user->id);

		if($user->balance < $this->$attribute){

			$this->addError($attribute, 'not enough money');

			return false;

		}

		return true;

	}	

}

Check this post Link

Here is the validator class for comma separated numbers https://gist.github.com/bizley-code/84b941a9fef12bf00267

Wouldn’t it be easier to just pass/enter values without any commas when you need to work with the values, and use commas only for display purposes?

Also, I think its better if you used something else other than FLOAT/DOUBLE when storing money values in your database (DECIMAL or NUMERIC should work in mysql) to prevent running into float rounding errors.

It is definitely better to keep float point number as decimal in mySQL but this case is not about storage but the user input.