Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation an integer input from a form

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?

like image 746
sprain Avatar asked May 06 '12 13:05

sprain


2 Answers

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.

like image 101
Paweł Jędrzejewski Avatar answered Oct 05 '22 08:10

Paweł Jędrzejewski


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))
     )
 ))
like image 21
Tony Knibb Avatar answered Oct 05 '22 07:10

Tony Knibb