Tuesday, January 25, 2022

[FIXED] CakePHP3: validate decimal input

Issue

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.


Solution

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


Answered By - Pradeep

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.