【问题标题】:How to validate empty input in Zend Framework 2如何在 Zend Framework 2 中验证空输入
【发布时间】:2015-08-12 06:50:51
【问题描述】:

我正在 ZF2 中填写注册表,但我不知道如何验证。验证似乎不起作用。

我正在添加验证器数组,但它无论如何都不起作用。我不知道我该如何解决。

这是我的控制器代码:

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Application\Form\Formularios;
use Zend\Db\Adapter\Adapter;
use Application\Modelo\Entity\Usuarios;

class FormularioController extends AbstractActionController
{
   public $dbAdapter;
    public function indexAction()
    {
        return new ViewModel();
    }
    public function registroAction()
    {

        if($this->getRequest()->isPost())
        {
            $this->dbAdapter=$this->getServiceLocator()->get('Zend\Db\Adapter');
            $u=new Usuarios($this->dbAdapter);
            //echo "se recibió el post";exit;
            $data = $this->request->getPost();


            $u->addUsuario($data);
             return $this->redirect()->toUrl($this->getRequest()->getBaseUrl().'/application/formulario/registro/1');

        }else
        {
            //zona del formulario
                                 $form=new Formularios("form");

             $id = (int) $this->params()->fromRoute('id', 0);
             $valores=array
            (
                "titulo"=>"Registro de Usuario",
                "form"=>$form,
                'url'=>$this->getRequest()->getBaseUrl(),
                'id'=>$id
            );
            return new ViewModel($valores);
        }

    }

}

这是我的带有验证器的表单代码

class Formularios extends Form
{
    public function __construct($name = null)
     {
        parent::__construct($name);

        $this->add(array(
            'name' => 'name',
            'required'    => true,
         'allow_empty' => false,
            'options' => array(
                'label' => 'Nombre Completo',
            ),
            'attributes' => array(
                'type' => 'text',
                'class' => 'input'
            ),
            'filters' => [ ['name' => 'StringTrim'], ],

            'validators' => array(
             array(
            'name' => 'NotEmpty',
            'options' => array(
                'messages' => array(
                    \Zend\Validator\NotEmpty::IS_EMPTY => 'Ingrese Nombres.',
                ))))
        ));

         $this->add(array(
            'name' => 'lastname',
            'required' => true,
            'options' => array(
                'label' => 'Apellido',
            ),
            'attributes' => array(
                'type' => 'text',
                'class' => 'input'
            ),
            'validators' => array(
        array(
            'name' => 'NotEmpty',
            'options' => array(
                'messages' => array(
                    \Zend\Validator\NotEmpty::IS_EMPTY => 'Ingrese Apellidos.',
                ))))
        )); 

提前致谢

【问题讨论】:

    标签: zend-framework2


    【解决方案1】:

    第一个问题。

    $data = $this->request->getPost(); 应该是$data = $this->getRequest()->getPost();

    第二个问题是当您在视图中构建表单时直接调用验证器,这是错误的。正确的做法是通过 inputFilter。现在,有很多方法可以做到这一点,例如:使用或不使用从模型中调用的工厂,或者通过带有表单元素管理器的 for 类

    我将向您展示工厂的示范方式,因为它对新手来说更容易。

    namespace MyModule\Model;
    
    use Zend\InputFilter\InputFilter;
    use Zend\InputFilter\Factory as InputFactory;
    use Zend\InputFilter\InputFilterAwareInterface;
    use Zend\InputFilter\InputFilterInterface;
    
    class MyModel implements InputFilterAwareInterface
    {
        /**
         * @var null $_inputFilter inputFilter
         */
        private $_inputFilter = null;
    
       // some more code like exhnageArray get/set method
    
        public function setInputFilter(InputFilterInterface $inputFilter)
        {
            throw new \Exception("Not used");
        }
    
        public function getInputFilter()
        {
            if (!$this->inputFilter) {
                $inputFilter = new InputFilter();
                $factory = new InputFactory();
                $inputFilter->add(
                    $factory->createInput([
                        'name'     => 'id',
                        'required' => false,
                        'filters'  => [
                            ['name' => 'Int'],
                        ],
                    ])
                );
                $inputFilter->add(
                    $factory->createInput([
                        "name"=>"title",
                        "required" => true,
                        'filters' => [
                            ['name' => 'StripTags'],
                            ['name' => 'StringTrim'],
                        ],
                        'validators' => [
                            ['name' => 'NotEmpty'],
                            [
                                'name'    => 'StringLength',
                                'options' => [
                                    'encoding' => 'UTF-8',
                                    'min' => 1,
                                    'max' => 200,
                                ],
                            ],
                        ],
                    ])
                );
                $inputFilter->add(
                    $factory->createInput([
                        "name"=>"text",
                        "required" => true,
                        'filters' => [
                            ['name' => 'StripTags'],
                            ['name' => 'StringTrim'],
                        ],
                        'validators' => [
                            ['name' => 'NotEmpty'],
                            [
                                'name'    => 'StringLength',
                                'options' => [
                                    'encoding' => 'UTF-8',
                                    'min' => 1,
                                ],
                            ],
                        ],
                    ])
                );
                $this->inputFilter = $inputFilter;
            }
            return $this->inputFilter;
        }
    
        }
    

    第三个问题。永远不要在控制器中使用 serviceManager。这是一个非常非常非常糟糕的做法。而是使用工厂。

    【讨论】:

    • 非常感谢。我使用 InputFIlter 并且可以使用 谢谢!
    猜你喜欢
    • 2017-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多