I have an entity with several fields in it. One of them is being validated after form submission as follows:
/**
* @var integer $anzahl
*
* @ORM\Column(name="anzahl", type="integer")
* @Assert\NotBlank(message="Bitte geben Sie eine Kistenanzahl an.")
* @Assert\Type(type="numeric", message="Die Kistenanzahl muss eine Zahl sein.")
* @Assert\Min(limit="1", message="Sie müssen mindestens eine Kiste suchen oder anbieten.")
*/
private $anzahl;
I am having two problems with this solution:
Only integer values higher than zero should be accepted. However also floats/doubles are being accepted by this validation. However, if I change @Assert\Type(type="numeric")
to @Assert\Type(type="integer")
no input is validated as true. How can I validate my input to be an integer value?
The other problem is, after entering an obviously invalid value (like a string of letters) I receive not only my German error message for Type validation but also the English message 'This value should be a valid number'. Where does this message come from and how can I get rid of it?
You should use:
@Assert\Type(type="integer")
But be careful, you should use it with an IntegerType
, not a NumberType
or a TextType
:
Symfony\Component\Form\Extension\Core\Type\IntegerType
IntegerType
is identical to NumberType
except that it integrates the proper data transformer.
This works for me:
->add('field_name', 'integer', array(
'label' => 'Your label here',
'data' => 0, // default value
'precision' => 0, // disallow floats
'constraints' => array(
new Assert\NotBlank(),
new Assert\Type('integer'),
new Assert\Regex(array(
'pattern' => '/^[0-9]\d*$/',
'message' => 'Please use only positive numbers.'
)
),
new Assert\Length(array('max' => 2))
)
))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With