Haithem Rihane
Haithem Rihane

Reputation: 394

Symfony form validation of decimal field

I am trying to use the Assert validation rule with decimal and it fails with error.

Here is my form

    $builder->add('cinp_number', 'number', array(
        'required' => false,
    ));

Here is my Entity

 /**
 * @Assert\Type(type="decimal")
 * @var decimal
 */
private $cinp_number;

This is the error when submiting form with string value as input:

Warning: NumberFormatter::parse(): Number parsing failed

LOG Message:

request.CRITICAL: Uncaught PHP Exception Symfony\Component\Debug\Exception\ContextErrorException: "Warning: NumberFormatter::parse(): Number parsing failed" at C:\wamp\www\top_service\vendor\symfony\symfony\src\Symfony\Component\Form\Extension\Core\DataTransformer\NumberToLocalizedStringTransformer.php line 174 {"exception":"[object] (Symfony\\Component\\Debug\\Exception\\ContextErrorException(code: 0): Warning: NumberFormatter::parse(): Number parsing failed at C:\\wamp\\www\\top_service\\vendor\\symfony\\symfony\\src\\Symfony\\Component\\Form\\Extension\\Core\\DataTransformer\\NumberToLocalizedStringTransformer.php:174)"} []

Symfony Version: 3.2.13

Upvotes: 0

Views: 5039

Answers (2)

Maksym  Moskvychev
Maksym Moskvychev

Reputation: 1674

To check that some value in form is decimal one can use following validators:

Range in case min/max values are defined http://symfony.com/doc/current/reference/constraints/Range.html

/**
 * @Assert\Range(min=0, max=100500)
 */
 private $cinp_number;

Regex if it's any number, here you can also define allowed format http://symfony.com/doc/current/reference/constraints/Regex.html

/**
 * @Assert\Regex("/^\d+(\.\d+)?/")
 */
 private $cinp_number;

IsTrue and check everyting manually in a custom method http://symfony.com/doc/current/reference/constraints/IsTrue.html

/**
 * @Assert\IsTrue()
 */
public function isCinpNumberValid()
{
    return $this->cinp_number == (float) $this->cinp_number;
}

Upvotes: 3

miikes
miikes

Reputation: 984

The Type constraint bases on is_<type>() or ctype_<type>() php functions. There is no decimal type in php definition.

Check out the list of supported types in Symfony Documentation or the list of Variable handling Functions / Ctype Functions in PHP REF.

In your case try numeric.

Upvotes: 2

Related Questions