How to check the price (amount of money) mySql decimal column in Yii?

I use the mySql DECIMAL column (12.4) to store price values ​​(seeing how Magento uses this). I want to test them in my ActiveRecord model using the Yii CValidator rules, but I'm not quite sure how to do this.

I suppose I can do this with the CTypeValidator set to "float", but I wanted to see how other people do it. I do not see a valid "currency" validator. Maybe I should just check the length?

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

or

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

Suggestions and examples? Thanks!

+4
source share
3 answers

I myself used:

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

... if necessary, you can also use or combine the previous one with the compliance validator

 array('price', 'match', 'pattern'=>'fancy regex magic here'), 
+10
source

To add a working example, since this is a general question (without a 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 integer digits, and {0,4} is the range of "under" units.

For a normal price range from 0.01 to 9999.99, use the regular expression as follows:

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

ref: kitune in the Yii forums

+5
source

To check the number you can use:

 array('price', 'numerical', 'integerOnly' => false, 'min' => 0), 

If you need to limit the digits before and after the decimal place, use regex as others suggested.

0
source

Source: https://habr.com/ru/post/1335904/


All Articles