我正在尝试找出如何从我的validate()数组中获取实际消息,该数组包含验证模型中提交内容的所有规则。
基本上我是张贴ajaxily并且我想返回验证失败的表单中的所有错误消息,但是即使它们已通过验证,它也会发送它们。
所以在我的
SubmissionsController
我这样做:
if ($this->request->is('ajax')) {
$formData = $this->Submission->invalidFields();
$this->set(compact('formData'));
}
在Submission
模型中,我有:
var $validate = array(
'title' => array(
'title' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a title'
),
'minLength' => array(
'rule' => array('minLength', 5),
'message' => 'Please make your title longer (e.g. IJL John F. Kennedy donated his presidential salary to charity)'
),
'maxLength' => array(
'rule' => array('maxLength', 300),
'message' => 'Your title needs to be shorter'
),
),
'description' => array(
'shortDescription' => array(
'rule' => array('shortDescription'),
'message' => 'Your description needs to be longer'
),
'longDescription' => array(
'rule' => array('longDescription'),
'message' => 'Your description needs to be shorter'
),
),
'source' => array(
'source' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Enter a valid source URL (e.g. http://en.wikipedia.org/wiki/Penguins)'
),
'website' => array(
'rule' => 'url',
'message' => 'Enter a valid source URL (e.g. http://en.wikipedia.org/wiki/Penguins)'
),
),
'category' => array(
'category' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Please choose a category'
)
)
);
在我的Submissions/json/submit.ctp
文件中,我有:
<?php
$fragment = $this->element('errors/flash_error');
$toReturn = array(
'formData' => $formData
);
echo json_encode($toReturn);
如果我输入有效的标题或任何其他有效字段,我仍然会收到错误消息而不是任何内容。
为了不返回已通过验证的字段,是否有invalidFields()
需要的东西?
编辑:
正如Leo在下面建议的那样,我在invalidFields()
正确的代码应该是:
if ($this->Submission->save($this->request->data)) {
$formData = null;
} else {
$formData = $this->Submission->invalidFields();
}
$this->set(compact('formData'));
答案 0 :(得分:0)
您正在通过save()调用或validates()调用invalidFields()而不进行验证!