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!
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'),
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With