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

12,604

Solution 1

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'),

Solution 2

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

Share:
12,604
thaddeusmt
Author by

thaddeusmt

I am a web developer and outdoor enthusiast. I mostly do HTML/CSS/JavaScript and PHP/MySql/MongoDB (on Apache/Nginx), but have dabbled in Java, .NET, Ruby, et al. I've done a lot of work with social APIs (Facebook, Twitter, Instagram), Drupal, WordPress, Magento, and the Yii framework, and also do server operations and administration. The phrase "full stack" comes to mind. I am currently the Chief Software Architect at http://splashlabsocial.com (built on Yii), where we build custom social media applications on top of our data platform.

Updated on June 04, 2022

Comments

  • thaddeusmt
    thaddeusmt almost 2 years

    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!