0

我试图找出如何从我的 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 在下面建议的那样,我之前没有调用 saveinvalidFields()

正确的代码应该是:

            if ($this->Submission->save($this->request->data)) {
                $formData = null;
            } else {
                $formData = $this->Submission->invalidFields();
            }
            $this->set(compact('formData'));
4

1 回答 1

0

您正在通过 save() 调用或 validates() 调用 invalidFields() 而不进行验证!

于 2012-06-25T17:53:20.673 回答