好的,我在这里有些沮丧。根据下面的代码,在Zend Framework 2中将'0'传递给必需的formfield似乎是不可能的,而不会导致状态变为'invalid'。
// FLOAT (0.0)
if ($type >= self::FLOAT) {
$type -= self::FLOAT;
if (is_float($value) && ($value == 0.0)) {
$this->error(self::IS_EMPTY);
return false;
}
}
// INTEGER (0)
if ($type >= self::INTEGER) {
$type -= self::INTEGER;
if (is_int($value) && ($value == 0)) {
$this->error(self::IS_EMPTY);
return false;
}
}
这段代码来自'Zend \ Validator \ NotEmpty',由inputFilterSpecification()方法中的'required = true'属性调用。
然后我的问题是:为什么?在我看来,0是一个完全有效的整数,而0.0是一个完全有效的浮点数。
另外:如何在保持'required = true'的同时避免这种验证?您仍然知道我的领域仍然是必需的。
这是我的表单元素:
$this->add(
array(
'name' => 'price',
'type' => 'Zend\Form\Element\Text',
'options' => array(
'label' => 'Price'
)
)
);
这是我的inputFilterSpecification:
'price' => array(
'required' => true,
'validators' => array(
array(
'name' => 'Float',
),
),
'filters' => array (
array(
'name' => 'Shop\Form\Filter\CurrencyFilter',
)
),
),
像这样从zf2扩展验证器类
namespace Application\Validator;
use Zend\Validator\NotEmpty;
class NotEmptyAllowZero extends NotEmpty {
public function isValid( $value ) {
$type = $this->getType();
// allow zero float
if($type >= self::FLOAT && $value == 0.0) {
return true;
}
// allow integer zero
if ($type >= self::INTEGER && $value == 0) {
return true;
}
// go on with zend validator
return parent::isValid( $value );
}
}
在模块配置中注册自定义验证器(例如Application / Config.php)
'service_manager' => array(
'invokables' => array(
'NotEmptyAllowZero' => 'Application\Validator\NotEmptyAllowZero'
)
)
并且您可以将其用作验证器(!not过滤器)
'price' => array(
'required' => true,
'validators' => array(
array(
'name' => '\Application\Validator\NotEmptyAllowZero',
),
),
'filters' => array (
array(
'name' => 'Shop\Form\Filter\CurrencyFilter',
)
),
),
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句