我希望在cakephp的控制器中验证。虽然我的验证在模型中运行良好,但我不希望在控制器中验证它。
我在控制器中做了什么验证。
$validates = array('email' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A email is required'
),
'isUnique' => array(
'rule' => array('notEmpty'),
'message' => 'This email is already registered'
),
'email' => array(
'rule' => array('email'),
'message' => 'Enter valid mail address'
)
));
if ($this->User->validates($validates)) {
die("Action can be performed as validated !! Fields are correct");
} else {
die("Action can't be performed !! Fields are in-correct");
}
如果字段正确与否,它总是以正确的状态告诉我。请帮忙
答案 0 :(得分:5)
设置$ this->模型 - > validates = $ validates;将按照上一个答案中的建议为您工作,但您可能会覆盖可能在模型中设置的所有其他验证规则。最好是动态添加,修改和删除验证规则,如下所示:
$this->Model->validator()
->add('email', 'required', array(
'rule' => array('notEmpty'),
'message' => 'A email is required'
))
->add('email', 'isUnique', array(
'rule' => array('notEmpty'),
'message' => 'This email is already registered'
))
->add('email', 'email', array(
'rule' => array('email'),
'message' => 'Enter valid mail address'
));
我完全按照您提供的方式离开了您的阵列,但我假设您在isUnique
上有错误的规则您可以在此处详细了解绑定规则:http://book.cakephp.org/2.0/en/models/data-validation.html#dynamically-change-validation-rules
答案 1 :(得分:2)
试试这个 -
$data = $this->request->data;
$this->ModelName->set($data);
if ($this->ModelName->validates()) {
// it validated logic
} else {
// didn't validate logic
$errors = $this->ModelName->validationErrors;
}
假设您要验证cakephp Controller中的特定字段,那么下面的代码将被使用 -
$this->ModelName->validationErrors['html_field_name'][] = 'Your Error Message goes here';
答案 2 :(得分:0)
编辑您的代码:
$this->$Model->validate = array('email' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A email is required'
),
'isUnique' => array(
'rule' => array('notEmpty'),
'message' => 'This email is already registered'
),
'email' => array(
'rule' => array('email'),
'message' => 'Enter valid mail address'
)
));
它与我合作:)