Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate a price (money amount) mySql decimal column in Yii?

I am using a mySql DECIMAL(12,4) column to hold price values (seeing how that's what Magento uses). I want to validate them in my ActiveRecord model using Yii's CValidator rules, but I'm not quite sure how to do it.

I assume I can do it with the CTypeValidator set to "float", but I wanted to see how other folks are doing this. I don't see an actual "currency" validator. Maybe I should just validate the length?

array('price', 'type', 'type'=>'float'),

or

array('price', 'length', 'max'=>17), // 12 + 4 + . = 17?

Suggestions and examples? Thanks!

like image 845
thaddeusmt Avatar asked Dec 07 '22 23:12

thaddeusmt


2 Answers

I myself used the:

array('price', 'type', 'type'=>'float'),

rule... if needed, you can also use or combine the previous with the 'match' validator

array('price', 'match', 'pattern'=>'fancy regex magic here'),
like image 119
ZaQ Avatar answered Jan 10 '23 13:01

ZaQ


To add a working example, as this is common question (with no good answer in SO)"

public function rules(){
...
array('price', 'match', 'pattern'=>'/^[0-9]{1,12}(\.[0-9]{0,4})?$/'),
...

where {1,12} is the range of whole digits , and {0,4} is the range of "sub" units.

For a normal price range of 0.01 to 9999.99 use the regex like this:

'/^[0-9]{1,0}(\.[0-9]{0,2})?$/'    

ref: kitune in Yii forums

like image 41
d.raev Avatar answered Jan 10 '23 14:01

d.raev