使用Zend framework 1.6,我收到这样的POST请求:
array(2) {
["checkins"] => array(18) {
["nome"] => string(6) "MYNAME" //the field is correctly filled
["pec"] => string(0) ""
["sito_web"] => string(0) ""
["note"] => string(0) ""
}
["users"] => array(19) {
["email"] => string(29) "email@gmail.com"
["u_id"] => string(1) "1"
}
}
验证' name '字段,我使用Zend输入过滤器。这是我的验证器数组:
$validators = array (
'nome' => array (
'presence' => 'required'
));
$params = $this->getRequest ()->getPost ();
$input = new Zend_Filter_Input ( array (), $validators,$params );
if (! $input->isValid ()) {
print_r($input->getMessages ());
}
似乎验证不是很好,因为我收到消息:
Field 'nome' is required by rule 'nome', but the field is missing
在我看来有一个错误在我的$validators数组,但我找不到它。
您的问题是,您在html表单中使用了数组符号。
你可以在你的html:
<form ...>
...
<input type="text" name="checkins[nome]" ... />
...
</form>
在表单元素中称为数组表示法。
你可以通过调用
在ZF中得到这个数组:$request = $this->getRequest();
if($request->isPost()) {
$post = $request->getPost();
$validators = array (
//nome has to be present and not empty
'checkins' => array(
'nome' => array(
'NotEmpty',
'presence' => 'required'
),
//if pec is present, it has to be not empty
'pec' => array(
'NotEmpty'
)
)
);
//validate the post array
$input = new Zend_Filter_Input( array(), $validators, $post);
if (!$input->isValid()) {
Zend_Debug::dump($input->getMessages());
}
Zend_Debug::dump($post);
}
但是有些事情发生了,我不明白…
如果使用下一种方法,一切都很好…
$request = $this->getRequest();
$checkins = $request->getPost('checkins');
$validators = array (
//nome has to be present and not empty
'nome' => array(
'NotEmpty',
'presence' => 'required'
),
//if pec is present, it has to be not empty
'pec' => array(
'NotEmpty'
)
);
//validate the checkins array instead of the whole array
$checkinsFilter = new Zend_Filter_Input( array(), $validators, $checkins);
if (!$checkinsFilter->isValid()) {
Zend_Debug::dump($checkinsFilter->getMessages());
}
希望有帮助。
阅读更多关于Zend_Validate_Input和元命令在这里:http://framework.zend.com/manual/1.6/de/zend.filter.input.html zend.filter.input.metacommands.presence
和更多可用的验证器类在这里:http://framework.zend.com/manual/1.6/de/zend.validate.set.html
也许可以考虑使用Zend_Form来生成一个对象,该对象包含您需要的所有验证器、过滤器和元素。您不需要使用此表单来呈现html输出。但是使用它来验证和过滤要比手动对所有类型的表单进行验证和过滤简单得多。
祝你玩得开心,好运!