zf2でバリデータを行うには?

zf2で入力チェックを行う場合、

Formで入力条件を設定し、入力チェックを行う方法があります。

 

書き方はこんな感じ。

 

class BrandFieldset extends Fieldset implements InputFilterProviderInterface
 {
     public function __construct()
     {
         parent::__construct('brand');

         $this
             ->setHydrator(new ClassMethodsHydrator(false))
             ->setObject(new Brand())
         ;

         $this->add(array(
             'name' => 'name',
             'options' => array(
                 'label' => 'Name of the brand',
             ),
             'attributes' => array(
                 'required' => 'required',
             ),
         ));

         $this->add(array(
             'name' => 'url',
             'type' => 'Zend\Form\Element\Url',
             'options' => array(
                 'label' => 'Website of the brand',
             ),
             'attributes' => array(
                 'required' => 'required',
             ),
         ));
     }

     /**
      * @return array
      */
     public function getInputFilterSpecification()
     {
         return array(
             'name' => array(
                 'required' => true,
             ),
         );
     }
 }

ここで定義しています。

$this->add(array(
             'name' => 'hoge',
             'options' => array(
                 'label' => 'Name of the brand',
             ),
             'attributes' => array(
                 'required' => 'required',
             ),
         ));

inputのname要素hogeの入力チェックを行っています。
attributesのなかに、requiredと書いてあるので、ここで空チェックを行います。
空チェック以外にも他にも入力チェックが用意されているので、
後日、紹介します。