Zend Framework 2 - 编写和设置一个好的InputFilter

时间:2015-06-20 19:14:47

标签: php forms validation zend-framework

我正在ZF2网站上创建一个表单,我已经解决了很多问题:  Zend Framework 2 - Submitting a form(也可以在那里查找代码) 现在我有另一个问题:在我的控制器中,form->isValid()无论如何都会返回true。我的目标是通过PHP进行验证,然后通过Ajax告诉用户一切是否正常。我想我的InputFilter出了问题,或者它没有正确地附在我的表格上 有什么建议?提前谢谢。

1 个答案:

答案 0 :(得分:0)

也解决了这个问题。 将所有验证器放在与表单相同的类中完成工作;这是(差)官方文档和一些论坛主题的混合在这里和其他地方。 Form类现在看起来像这样:

<?php
namespace Site\Form;

use Zend\Form\Form;
use Zend\Form\Element;
use Zend\InputFilter\Input;
use Zend\InputFilter\InputFilter;
use Zend\Validator;

class ContactForm extends Form {
    public function __construct($name=null, $options=array ()) {
        parent::__construct ($name, $options);

        $this->setAttributes(array(
            "action" => "./",
        ));


        $nameInput = new Element\Text("nome");
        $nameInput->setAttributes(array(
            "placeholder" => "Nome e cognome",
            "tabindex" => "1"
        ));

        $this->add($nameInput);

        $emailInput = new Element\Text("email");
        $emailInput->setAttributes(array(
            "placeholder" => "Indirizzo e-mail",
            "tabindex" => "2"
        ));

        $this->add($emailInput);

        $phoneInput = new Element\Text("phone");
        $phoneInput->setAttributes(array(
            "placeholder" => "Numero di telefono",
            "tabindex" => "3",
        ));

        $this->add($phoneInput);

        $messageArea = new Element\Textarea("messaggio");
        $messageArea->setAttributes(array(
            "placeholder" => "Scrivi il tuo messaggio",
            "tabindex" => "4"
        ));

        $this->add($messageArea);

        $submitButton = new Element\Button("submit");
        $submitButton
            ->setLabel("Invia messaggio")
            ->setAttributes(array(
                "type" => "submit"
            ));

        $this->add($submitButton);

        $resetButton = new Element\Button("reset");
        $resetButton
        ->setLabel("Cancella")
        ->setAttributes(array(
                "type" => "reset"
        ));

        $this->add($resetButton);

        $inputFilter = new InputFilter();

        $nome = new Input("nome");
        $nome->getValidatorChain()
        ->attach(new Validator\StringLength(3));

        $email = new Input("email");
        $email->getValidatorChain()
        ->attach(new Validator\EmailAddress());

        $phone = new Input("phone");
        $phone->getValidatorChain()
        ->attach(new Validator\Digits());

        $message = new Input("messaggio");
        $message->getValidatorChain()
        ->attach(new Validator\StringLength(10));

        $inputFilter->add($nome)
                    ->add($email)
                    ->add($phone)
                    ->add($message);

        $this->setInputFilter($inputFilter);
    }
}
?>

我稍后会尝试工厂,但就目前来说,这是有效的。