Quantcast
Channel: Yii Framework Forum
Viewing all articles
Browse latest Browse all 18717

Sanitizing Currency

$
0
0
Hello,

I am currently using an application that stores and retrieves currency from the database. I use the CNumberFormatter class to properly format a number when retrieved and presented in a view, but I noticed there is no method to "un-format" the number when storing it in the database. I searched the forum and found an extension, but I'm not too fond of using extensions for this project.

Since Yii rules validate both client and server side, wouldn't it just be acceptable to define a rule that only accepts floating point numbers and define something for the beforeValidate() method in the model to sanitize.

I came up with this:

#Validation rules

array('balance', 'required'),
array('balance', 'length', 'max'=>19),
array('balance', 'type', 'type'=>'float', 'message'=>'Should be in the following format: 00.00 (Ex. 12.25)'),	


#Money Model

public function beforeValidate()
{
  if(!empty($this->balance)) {
    $search = array("$",",");
    foreach($search as $nonInteger) {
      $this->balance=str_replace($nonInteger,'',$this->balance);
    }
    return $this->balance;
  }
 return  parent::beforeValidate();											
}


This code in particular would accept currency formatted in U.S. dollars, as well as commas. However, those values would be stripped. Everything else would fail validation. So "$123,456.78", "$123", "123,456.78" would all be valid. Is there a better method to doing this, or would this be considered an acceptable way of implementing what I am looking for?

Thank you in advance!

Cody

Viewing all articles
Browse latest Browse all 18717

Trending Articles