如何在cakePHP中进行验证?

时间:2012-05-03 10:31:41

标签: php validation cakephp

在验证为真之前,我将添加到控制器以显示消息和暂停保存?

class Rsvp extends AppModel {
var $name = 'Rsvp';
var $validate = array(
                'uname' => array(
                                'rule' => array('alphaNumeric', true),
                                'message' => 'Please enter a vlaid name that does not contain digits'),
                'uemail' => array(
                                'rule' => array('email', true),
                                'message' => 'Please supply a valid email address.')


);

}

控制器

public function add() {


    if ($this->request->is('post')) {

        var_dump($this->request->data);
        $this->Rsvp->set('uname', $this->request->data['Post']['name']);
        $this->Rsvp->set('uemail', $this->request->data['Post']['emailaddress']);           
          //Begin Validation Routine
        echo 'Validation';
        var_dump($this->Rsvp->validates);


        $this->Rsvp->save();    
        /*if($this->Rsvp->save()) {
            $this->Session->setFlash('You have RSVP for the event');
           // $this->redirect(array('action' => 'index'));              
        }
        else {
            $this->Session->setFlash('Unable to RSVP you for the event.');
        }*/
    }
}

2 个答案:

答案 0 :(得分:2)

你的意思是:

if($this->Rsvp->validates()) {
   //data validated, so save
   $this->Rsvp->save($this->data);    
}
else {
   $this->Session->setFlash(__('Fill in all required fields.', true));
}

答案 1 :(得分:0)

默认情况下,Model::save()方法会自动验证。因此,只需尝试保存即可完成验证:

if ($this->request->is('post')) {
  if ($this->Rsvp->save($this->request->data)) {
    // validated and saved to db
  } else {
    // didn't validate or failed saving to db
  }
}

如果您不想验证,请使用

$this->Rsvp->save($this->request->data, array('validate' => false));

最后,您可以通过设置数据并运行validates()方法来手动验证。

$this->Rsvp->set('uname', $this->request->data['Post']['name']);
$this->Rsvp->set('uemail', $this->request->data['Post']['emailaddress']);
$validates = $this->Rsvp->validates();

如果它没有验证,它将设置$this->Rsvp->validationErrors,然后在控制器上设置它,表单助手将知道这些错误并自动为您显示它们。

您可以在书中了解有关保存数据和数据验证的更多信息:http://book.cakephp.org/2.0/en/models/saving-your-data.html