簡體   English   中英

Zend Framework 2-編寫和設置良好的InputFilter

[英]Zend Framework 2 - Writing and setting a good InputFilter

我正在ZF2網站上創建表單,在這里我已經解決了許多問題: Zend Framework 2-提交表單 (也可以在此處查找代碼)。
現在我有另一個問題:在我的控制器中,無論如何, form->isValid()返回true。 我的目標是通過PHP進行驗證,然后通過Ajax告訴用戶是否一切正常。 我想我的InputFilter出了點問題,或者未正確附加到我的表單上。
有什么建議么? 提前致謝。

也解決了這一問題。 將所有驗證者放在與表格相同的類別中; 這是(差的)官方文檔以及此處以及其他地方的一些論壇主題的混合體。 表單類現在看起來是這樣的:

<?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);
    }
}
?>

稍后我將嘗試工廠,但是現在可以了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM