CakePHP3: validate decimal input

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:


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?

1 - create a javascript decimal mask to ur input
2 - parse entity property (price) to float at its creation (set) and use the decimal() validator, or use a custom validate function:

    'validateDecimal', [
        'rule' => function ($value, $context) {
          //decimal validate code here that must return true/false;
        'message' => 'Incorrect decimal format'
1 Like