通过cakephp中的特定规则进行验证

时间:2015-05-04 12:36:17

标签: cakephp-2.0

我对特定字段有4条规则。但我想验证一个特定的规则。如何做cakephp2.0

是否有任何解决方案

1 个答案:

答案 0 :(得分:1)

我认为你有一个模特&声明了像

这样的字段的规则集
//in your model

    public $validate = array(
        'first_name' => array(
            'rule-1' => array(
                'rule' => 'alphaNumeric',
                'message' => 'Only alphabets and numbers allowed',
            ),
            'rule-2' => array(
                'rule' => array('minLength', 8),
                'message' => 'Minimum length of 8 characters'
            )
        ),
    );

在这里,您可以看到我为字段first_name定义了两个规则。现在我尝试删除loginRule-2之类的

// in your controller 

    public function add() {
        if ($this->request->is('post')) {
            $this->User->create();

           // // Completely remove all rules for a field
            $this->User->validator()->remove('first_name');
            $this->User->validator()->add('first_name', 'required',
            array(
               'rule' => 'notEmpty'
            ));
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('The user has been saved.'), 'default', array('class' => 'alert alert-success'));
                return $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.'), 'default', array('class' => 'alert alert-danger'));
            }
        }
    }

您可以查看CakePHP Cookbook 2.x documentation for Removing rules from the set

就是这样。