dongzhuang1923
2012-12-04 16:27
浏览 29
已采纳

ZF2未使用InputFilter验证输入

I am trying to create a single abstract class to manage input validation - in this class I have static functions that return InputFilterInterface objects that I can then add to my interface in the model class that handles the data. However, none of the data ever seems to be validated even though it is valid. I am not using Forms, by the way - the data is coming in via Ajax rather than an HTML form.

Here is my code:

Central Library:

abastract class InputFilters {
    public static function monthIDFilter($fieldName = 'monthID', $required = FALSE) {
        $factory = new InputFactory();
        return $factory->createInputFilter(array(
            $fieldName => array(
                'name' => $fieldName,
                'required' => $required,
                'validators' => array(
                    array('name' => 'not_empty'),
                    array('name' => 'string_length', 'options' => array(
                        'min'=>'6', 'max'=>'6'
                    )),
                    array('name' => 'regex', 'options'=>array(
                        'pattern' => '/^[0-9]{6}$/'
                    ))
                ),
            )
        ));
    }
}

Model:

class DataModel implements \Zend\InputFilter\InputFilterAwareInterface {
    protected $_inputFilter;

    public function __construct()
    {
        $this->setInputFilter(InputFilters::monthIDFilter());
    }

    public function setInputFilter(InputFilterInterface $inputfilter)
    {
        if(!$this->_inputFilter) {
            $this->_inputFilter = new InputFilter();
        }
        $this->_inputFilter->add($inputfilter);
    }

    public function getInputFilter()
    {
        if(!$this->_inputFilter) {
            $this->_inputFilter = new InputFilter();
        }
        return $this->_inputFilter;
    }
}

And finally, in the controller:

public function dataAction()
{
    $model = new DataModel();
    $inputFilter = $model->getInputFilter();
    $inputFilter->setData($_REQUEST);
    print_r($_REQUEST);
    print_r($inputFilter->getValues());
    if ($inputFilter->isValid()) {
        if ($inputFilter->has('monthID')) {
            echo $inputFilter->getValue('monthID');
            $formMonth = $inputFilter->getValue('monthID');
        } else {
            echo 'nope';
            $formMonth = '';
        }
        $grid->setSqlString($formMonth);
        $data = $grid->outputData();
        Json::out($data);
    }

In my output, I see the input that contains my monthID (201212) and an array that should be the validation results: Array ( [] => Array ( [monthID] => ) ) and the word 'nope' indicating that the has('monthID') check failed.

Any advice as to where I went wrong?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题