【发布时间】:2024-05-16 12:40:01
【问题描述】:
我正在尝试找出如何从我的 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() 之前没有调用 save
正确的代码应该是:
if ($this->Submission->save($this->request->data)) {
$formData = null;
} else {
$formData = $this->Submission->invalidFields();
}
$this->set(compact('formData'));
【问题讨论】:
-
这可能会有所帮助... [1]:*.com/questions/7854369/…
-
bob 你在哪里做验证?您似乎只是在没有保存或验证的情况下调用 invalidfields()?
-
@Leo 哇,我(不)到底在想什么?完全忽略了这一点。谢谢!
标签: php validation cakephp