2

I am trying to have a form with float number validation. when validation works it won't let me click the submit button and will show the proper error message.

I am using zend framework 2 and in my Form I want to retrieve alcohol volume.

I'm trying to use the following code:

$this->add($factory->createElement(array(
            'name' => 'alcohol_vol',
            'attributes' => array(
                    'label' => 'alcohol vol%:',
                    'filters'    => array('Float'),
                    'type'  => 'text',
                    'required'   => true,
            ),
    )));

this doesn't do anything actually. it will pass validation if i enter regular text.

I also tried changing the type to 'Number' from 'text' but then it won't allow me to use floating number. it will allow only none-float numbers :)

4

3 回答 3

2

ZF2 中没有“Float”过滤器,我想您可能想要的是“Float”验证器,Float Validator 可以像这样添加到 ZF2 表单中:

$this->add($factory->createElement(array(
        'name' => 'alcohol_vol',
        'attributes' => array(
                'label' => 'alcohol vol%:',
                'type'  => 'text',
        ),
)));
$factory = new Zend\InputFilter\Factory();

$this->setInputFilter($factory->createInputFilter(array(
    'alcohol_vol' =>     array(
        'name' => 'alcohol_vol',
        'required' => true,
        'validators' => array(
            array(
                'name' => 'Float',
            ),
        ),
    ),
)));

然后你应该在控制器中验证表单,上面的验证器仍然应该设置为表单。如果输入不是浮动的,则输入元素将具有无效消息:

$form->setData($userInputData);
if (!$form->isValid()) {
  $inputFilter = $form->getInputFilter();
  $invalids = $inputFilter->getInvalidInput();
  var_dump($invalids);
  // output: 'abc' does not appear to be a float
}
于 2012-07-01T12:31:09.923 回答
1

我认为您可以使用此过滤器

new Zend\I18n\Filter\NumberFormat("en_US", NumberFormatter::TYPE_DOUBLE);

于 2013-01-18T06:22:27.103 回答
0

我推荐 Zend\I18n\Validator\Float 类。示例用法:

$floatInput = new Input('myFloatField');
$floatInput->getValidatorChain()
           ->attach(new \Zend\I18n\Validator\Float());

看:

于 2014-06-12T19:33:15.413 回答