Arockiam Shakespeare
Arockiam Shakespeare

Reputation: 21

Validate by specific rule in cakephp

I have 4 rules for specific field. But I want to validate for one specific rule. How to do in cakephp2.0

Is there any solution for that

Upvotes: 1

Views: 175

Answers (1)

Supravat Mondal
Supravat Mondal

Reputation: 2594

I assume that you have a model & declared set of rules for a field like

//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'
            )
        ),
    );

Here you see i have define two rules for field first_name. Now I try to remove loginRule-2 like

// 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'));
            }
        }
    }

You can look CakePHP Cookbook 2.x documentation for Removing rules from the set

That's it.

Upvotes: 1

Related Questions