[solved] CNumberValidator

I’ve created a price field in my database of type DECIMAL(6,2) so that I can store the price in the format 150.00 or 150.29

Now how can I validate this on my form so that the only acceptable formats are whole integer numbers i.e. "150" or numbers with two decimal places, i.e. "150.29".

I tried to use the CNumberValidator but it fails on the values with two decimal places, which I assume is because of the dot.

Try using Decorator pattern to decorate values like this at the view only.

Configure your decorator to "rollback" the string when bringing it back to server.

You can try writing your own validation method (if necessary).

You could try the Regular Expression Validator, e.g.




public function rules()

{

    [...]

    array('price', 'match', 'pattern'=>'/([1-9][0-9]*?)(\.[0-9]{2})?/'),

    [...]

}



BTW is that the best way ( DECIMAL(6,2) ) for storing currency values?

And any better way to perform the validation?

BUMP. Any more suggestions? Another thing is if the user enters the currency symbol (£) it should give an error.

This seems to be working:


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

use this:


array('price', 'match', 'pattern'=>'/^[0-9]{1,3}(\.[0-9]{0,2})?$/'),

to validate xxx.xx; 1-3 and 0-2 in this case.