2

This is probably a trivial question, but I can't figure it out.

I want my price value to have 2 decimal places. CakePHP should validate this, but it doesn't. CakePHP only checks if the input is a number and doesn't allow to pass decimal values.

I want it to check and pass values like 2.22 but also 2. Now it only allows the latter.

Part of validationDefault method:

$validator
    ->decimal('price')
    ->allowEmpty('price');

I checked CakePHP API and found decimal() method description:

decimal( float $check , integer|null $places null , string|null $regex null )

Checks that a value is a valid decimal. Both the sign and exponent are optional.

But it does not take string as a parameter in this context(and CakePHP assign decimal() to my price column automatically during baking), so I guess this is why decimal('price', 2) don't work.

Any ideas?

REQUESTED EDIT:

Whole validationDefault method:

public function validationDefault(Validator $validator)
{

   //$validator for other columns

  $validator
        ->allowEmpty('price')
        ->add('price', 'money', array('rule' =>
                          array('money', 'left'),
                          'message' => 'Please supply a valid monetary amount.'));

  return $validator;
}

My input field is created using HTML helper.

1 Answer 1

1

You should use money to validate price

 $validator->notEmpty('price',array('message' => 'Please provide your amount'))     
              ->add('price', 'money', array('rule' => array('money','left'),
                                            'message' => 'Please supply a valid monetary amount.'));

Your can also try this

  $validator->notEmpty('amount',array('message' => 'Please provide your amount'))
            ->add('amount','numeric',array('rule' => 'numeric' ,'message'=> 'Please provide a valid amount'));
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your response. I copy-paste this line of code (and remove previous decimal('price')) but it still want only whole numbers.
try by removing 'left' its optional ,if not work show me your validation code
Well, this is embarrassing. Like really embarrassing. I didn't change my table settings in database to accept decimal values (I've got decimal(10,0) instead of decimal(10,2)). After fixing it and clearing cache of the app, everything works. I'm sorry for that stupid question and I thank you for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.