3

我希望在 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");
            }

无论字段是否正确,它总是让我处于正确的状态。请帮忙

4

3 回答 3

7

设置 $this->Model->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

于 2014-10-22T10:20:51.357 回答
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 控制器中的特定字段,那么将使用以下代码 -

$this->ModelName->validationErrors['html_field_name'][] = 'Your Error Message goes here';
于 2014-11-23T11:43:05.970 回答
1

编辑您的代码:

$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'
                    )
            ));

它和我一起工作:)

于 2014-10-22T09:51:08.817 回答