Decimal check in symfony 2

I have a symfony2 object mapped to a table using Doctrine. One of the properties:

/** * @var decimal $price * * @ORM\Column(name="price", type="decimal", nullable=false) */ private $price; 

What does Assert satisfy my requirement that $price must be a valid decimal?

If I leave everything as it is, I pass the string foo , since the decimal value will lead to a verification error, and the transmission of the NaN string will pass the test, because the NaN string is displayed as float(NaN) , thus, it is treated as a real decimal value.

Any workarounds?

Symfony dev team says this is not a problem: https://github.com/symfony/symfony/issues/3161

Well, if that is not the case, then there is probably a solution for checking it. Any ideas?

+5
source share
4 answers

From a look at the Symfony documentation, there is no built-in validator for decimals. You can use a callback validator, or, even better, you can create your own validator similar to this article here. .

As for the actual validation, I would use a combination of is_numeric and is_float to validate. There are methods using regular expressions, but, in my opinion, if the value satisfies either the is_numeric or is_float , then you can safely assume that this is a valid decimal (or integer).

EDIT:

Perhaps the best solution would be to check the decimal number as a string. Sort of...

 $stringDecimal = strval($decimalValue); return (preg_match(/[0-9]+(\.[0-9][0-9]?)?/, $stringDecimal) !== 0); 

While this is not perfect (you can easily pass "1.15adowadjaow" and it will check), it serves as the basis for what you need. Combining the above regex with something that searches for anything other than 0-9, fullstop, or a comma (depending on whether you want to use European decimal formatting).

+6
source

you can try a custom validator that only checks this string.

+2
source

If you use a form type for writing

  ->add( 'amount', 'text', change text to number and it will be validated [ 'required' => true ] ) 

Or you can use range assert

  • @Assert \ Range (min = 0)

he will check that he must be a number

+2
source

You can simply use @Assert\Type(type="Numeric") . Tested in symfony 3.4, but I think it will work with previous versions. E.G.

  /** * @var float * * @ORM\Column(name="cost", type="decimal", precision=10, scale=4) * @Assert\Type(type="Numeric") */ private $cost; 

Thanks!

0
source

Source: https://habr.com/ru/post/1392571/


All Articles