Symfony form validation of decimal field

99封情书 提交于 2020-12-16 07:08:06

问题


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


回答1:


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.




回答2:


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;
}


来源:https://stackoverflow.com/questions/45895022/symfony-form-validation-of-decimal-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!