题
有没有办法在登录表单上使用验证器 简单的锂认证 教程。我知道最好在模型中使用验证,但是使用登录表单没有模型,因此,据我了解,我需要在 SessionsController 中使用 Validator,但我不知道该怎么做(
我想做的是在 SessionsController 中:
<?php
namespace app\controllers;
use lithium\security\Auth;
use lithium\storage\Session;
use lithium\util\Validator;
class SessionsController extends \lithium\action\Controller {
private $rules = array(
'password' => array(
array('notEmpty', 'message' => 'password is empty'),
),
'email' => array(
array('notEmpty', 'message' => 'email is empty'),
array('email', 'message' => 'email is not valid')
)
);
public function add() {
if ($this->request->data && Auth::check('default', $this->request)) {
return $this->redirect('/');
}
// Handle failed authentication attempts
$errors = Validator::check($this->request->data, $this->rules);
return compact('errors');
}
public function delete() {
Auth::clear('default');
return $this->redirect('/');
}
/* ... */
}
我预计在发送空表单后,它将出现错误,就像在教程中创建用户一样。但没有显示任何错误,只需重新登录表单即可。我是否可以在没有模型的情况下验证表单以及如何在 Lithium 中进行验证?
预先感谢。
解决方案
表单中呈现的错误绑定到一个实体,当您使用以下命令创建表单时,该实体绑定到表单 $this->form->create($user)
. 。仅在这种情况下,表单助手会自动显示错误。
如果您需要在控制器中检查传入的数据,您可以检查 $this->request->data['password']
并返回您需要在表单视图中自行处理的错误(使用 if (!empty($errors))
例如)
不隶属于 StackOverflow