根据官方文档,use validators "not_empty"
use Zend\InputFilter\Factory;
$factory = new Factory();
$inputFilter = $factory->createInputFilter(array(
'password' => array(
'name' => 'password',
'required' => true,
'validators' => array(
array(
'name' => 'not_empty',
),
array(
'name' => 'string_length',
'options' => array(
'min' => 8
),
),
),
),
));
$inputFilter->setData($_POST);
echo $inputFilter->isValid() ? "Valid form" : "Invalid form";
奖金
Zend Framework 2 为您的表单提供了很多工具。
Fieldset
这是和的一个很好的例子InputFilterProviderInterface
。如果您使用 Doctrine,您还可以使用“Hydrator”将表单自动绑定到您的实体中。使用此代码没有问题required => false
就足够了,并且允许空字符串
class AddressFieldset extends Fieldset implements InputFilterProviderInterface {
public function __construct(ServiceManager $serviceManager) {
parent::__construct('attribute');
// $em = $serviceManager->get('Doctrine\ORM\EntityManager');
// $this->setHydrator(new DoctrineHydrator($em, 'MyProject\...\Entity\AddressEntity'))->setObject(new AddressEntity());
$this->add(array(
'name' => 'id',
'type' => 'Zend\Form\Element\Hidden',
'attributes' => array(
'autocomplete' => 'off'
)
));
$this->add(array(
'name' => 'name',
'options' => array(
'label' => 'Address'
),
'attributes' => array(
'class' => 'span3',
'autocomplete' => 'off'
)
));
$this->add(array(
'name' => 'district',
'options' => array(
'label' => 'District'
)
));
$this->add(array(
'name' => 'postal_code',
'options' => array(
'label' => 'Postal code'
)
));
$this->add(array(
'name' => 'city',
'options' => array(
'label' => 'City'
)
));
}
public function getInputFilterSpecification() {
return array(
'name' => array(
'required' => false,
),
'address' => array(
'required' => true,
),
'district' => array(
'required' => false,
),
'postal_code' => array(
'required' => true,
),
'city' => array(
'required' => true,
)
);
}
}
然后你创建一个包含你的字段集的表单
官方文档中非常好的示例,如果您控制 Form Fieldset 和 Hydrator(用于您的数据库),您将赢得很多时间。当然,在我的示例中,我指定是否需要输入,您也可以添加自定义验证器。
http://framework.zend.com/manual/current/en/modules/zend.form.collections.html