Ed Hoop
Ed Hoop

Reputation: 13

CakePHP does not validate fields

So i use CakePHP 2.0.5 .

My model:

class User extends AppModel {
public $name = 'User';
public $validate = array(
    'username' => array(
        'required' => array(
            'rule' => array('notEmpty'),
            'message' => 'A username is required'
        )
    ));}

Then i at controller perform this action it works fine and gives me error because the field username is empty:

$this->User->create();
$this->User->save(array("User"=>array("username"=>"")))

But if i pass the other named field like:

$this->User->create();
$this->User->save(array("User"=>array("something"=>"")))

it does not perform validation on username field and saves empty on database even if i made rule in my model that username value cannot be empty. So where i am wrong?

Upvotes: 1

Views: 2789

Answers (2)

Dave
Dave

Reputation: 29121

According to this page, it should be:

'rule' => 'notEmpty'

(notice the lack of an array surrounding the 'notEmpty')

Although it is shown that way (above) in the CakePHP book in a few places, I personally like doing it like this, as it seems to follow the rest of the validation conventions (and is shown in many places throughout the book as well):

'allowEmpty' => false,

Secondly, you need to understand the difference between "allowEmpty/notEmpty" and "required". According to this page:

The difference between required and allowEmpty can be confusing. 'required' => true means that you cannot save the model without the key for this field being present in $this->data (the check is performed with isset); whereas, 'allowEmpty' => false makes sure that the current field value is nonempty, as described above.

Basic translation: 'required' means any time you save that item, you MUST include that field. While 'allowEmpty'..etc means IF you pass that field, it can't be empty.

Upvotes: 2

Dunhamzzz
Dunhamzzz

Reputation: 14798

You need required => true in your validation rules, this will make validation fail if the username key is not supplied. I recommend pairing it with on => create so it wonly happens when the row is created.

$validate = array(
'username' => array(
    'not-empty' => array(
        'rule' => array('notEmpty'),
        'message' => 'A username is required',
        'required' => true,
        'on' => 'create'
    ),

));

Upvotes: 0

Related Questions