【问题标题】:Zend Framework - integer validatorZend Framework - 整数验证器
【发布时间】:2013-04-18 16:51:31
【问题描述】:

Zend Framework 似乎有一个验证整数的功能(为此检查了库中的 /Validate/Int.php),它可以正确地将浮点数验证为整数,而我想在给出浮点数时显示错误。

这是我表单中的一个 sn-p:

  $form['my_int'] = new Zend_Form_Element_Text('my_int');
  $form['my_int']->setLabel('My Int')
                 ->setRequired(true)
                 ->addFilter('StringTrim')
                 ->addDecorator('Errors', array('placement'=>'prepend', 
                                                'class'=>'my-err'))
                 ->addValidator('NotEmpty', true, array('messages' => 
                     array('isEmpty' => 'Please provide data')))
                 ->addValidator('int', true, array(
                     'locale' => 'en_US', 
                     'messages' => array(
                          'intInvalid' => 'Please provide valid data',
                          'notInt' => 'Please provide valid data'
                     )
                 ));

因此,当我提供不同于字符串、整数或浮点数的内容时,会触发“intInvalid”错误并显示我的自定义消息。当提供像 1.23 这样的浮点数时,会显示“notInt”错误。问题是当你提供例如1.00,然后验证器检查“!Zend_Locale_Format::isInteger($value, array('locale' => $this->_locale))”并确定输入是整数,并且当您尝试在数据库中添加浮点数时在整数字段中,您会得到错误。

我应该如何组织我的表单验证,以便在提供浮点数时,无论如何,向用户显示错误?

【问题讨论】:

    标签: php zend-framework


    【解决方案1】:

    您应该将 Int 过滤器添加到该元素。

    $element->addFilter(new Zend_Filter_Int());
    

    【讨论】:

    • 好的,但这会将所有输入转换为整数,不是吗?这样输入 1.99 将插入 1 并且不会向用户返回错误。还提供一些像'test'这样的字符串会将其转换为0,如果是有效值,将添加零并将其保存到数据库中?
    • 好吧,那么。您可以在表单通过验证后应用过滤器,例如,当您调用 getValidValues() 时。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-09
    • 1970-01-01
    • 1970-01-01
    • 2014-06-22
    • 1970-01-01
    相关资源
    最近更新 更多