2

我班上有这个

$inputFilter->add(
                    $factory->createInput(array(
                        'name' => 'precio',
                        'required' => true,
                        'validators' => array(
                            array(
                                'name' => 'Float',
                                'options' => array(
                                    'min' => 0,
                                ),
                            ),
                        ),
                    ))
            );

当我输入像 5 或 78 这样的整数时,一切似乎都正常,但是当我尝试使用像 5.2 这样的数字时,我收到了下一条错误消息

输入似乎不是浮点数

4

3 回答 3

5

Float Validator 类中的十进制字符取决于应用程序中使用的语言环境。尝试将语言环境添加为这样的选项:

$factory->createInput( array(
    'name' => 'precio',
    'required' => true,
    'validators' => array(
        array(
            'name' => 'Float',
            'options' => array(
                'min' => 0,
                'locale' => '<my_locale>'
            ),
        ),
    ),
) );

如果您不设置语言环境,则 Float 类获取php.ini 中定义的intl.default_locale

于 2014-01-22T12:01:06.420 回答
1

您可以像这样编写自己的验证器:

class Currency extends \Zend\Validator\AbstractValidator {

    /**
     * Error constants
     */
    const ERROR_WRONG_CURRENCY_FORMAT = 'wrongCurrencyFormat';

    /**
     * @var array Message templates
     */
    protected $messageTemplates = array(
        self::ERROR_WRONG_CURRENCY_FORMAT => "Vaule is not valid currency format. (xxx | xxx.xx | xxx,xx)",
    );

    /**
     * {@inheritDoc}
     */
    public function isValid($value) {

        $exploded = null;
        if (strpos($value, '.')) {
            $exploded = explode('.', $value);
        }
        if (strpos($value, ',')) {
            $exploded = explode(',', $value);
        }

        if (!$exploded && ctype_digit($value)) {
            return true;
        }
        if (ctype_digit($exploded[0]) && ctype_digit($exploded[1]) && strlen($exploded[1]) == 2) {
            return true;
        }
        $this->error(self::ERROR_WRONG_CURRENCY_FORMAT);
        return false;
    }

}

和过滤值:

class Float extends \Zend\Filter\AbstractFilter {

public function filter($value) {                    
    $float = $value;

    if($value){
        $float = str_replace(',', '.', $value);            
    }

    return $float;
}    

}

于 2015-09-16T08:17:14.687 回答
0

你可以使用回调验证器。

use Zend\Validator\Callback;
$callback = new Callback([$this, 'validateFloat']);
$priceCallBack->setMessage('The value is not valid.');

然后,在课堂上的某个地方你需要有这个功能。

public function validateFloat($value){
return (is_numeric($value));
}

最后在表单中,添加这个验证器,例如。

$this->inputFilter->add([
            'name'=>'pro_price',
            'required' => true,
            'validators'=>[$callback]
        ]);
于 2015-01-22T16:12:04.000 回答