[英]how to validate form field in cakephp using model and controller
我創建了一個需要使用模型和控制器進行驗證的表單。這是我的表單
index.ctp
<?php echo $this->Form->create('Contact',array('url'=>array('controller'=>'contacts','action'=>'add')));
echo $this->Form->text('name');
型號:Contact.php
class Contact extends AppModel
{
var $name = 'Contact';
var $useTable = false;
public $validate = array(
'name' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => false,
'message' => 'Letters and numbers only'
),
'between' => array(
'rule' => array('between', 5, 15),
'message' => 'Between 5 to 15 characters'
)
)
);
}
控制器:ContactsController.php
public function add()
{
$this->Contact->validates();
$this->request->data['Country']['country_name']=$this->request->data['Contact']['country'];
$this->Country->saveall($this->request->data);
$this->redirect('/Contacts/index/');
}
我正在嘗試通過谷歌搜索來進行驗證,但是對我來說似乎很難,因此如果有人可以描述該過程,那將是一個很大的幫助。我的cakephp版本為2.3.8。 我只需要驗證此名稱字段,因為當我單擊“提交”時,它將在表單中顯示此消息。
您的控制器代碼應類似於:CakePHP中的驗證過程類似於
1) as you have defined validation rules in CakePHP model public `$validates = array();`
2) when ever you do a save on particular model directly or through any association
a callback method beforeValidate for that model gets called to validate the data which is being saved.
3) once the data is validated then beforeSave callback is called after this save method is called.
4) we can also validate the form input fields in controller using $this->Model->validates() but then while saving we have to disable the beforeValidate callback by doing
$this->Model->save($data,array('validate'=>false));
否則,您將結束兩次驗證相同數據的操作
您的控制器代碼應該是這樣的。
public function add() {
// here we are checking that the request is post method
if ($this->request->is('post')) {
$this->request->data['Country']['country_name']
= $this->request->data['Contact']['country'];
// here we are saving data
if ($this->Contact->saveAll($this->request->data)) {
//here we are setting a flash message for user
$this->Session->setFlash('your record has been added','success');
$this->redirect(array('controller'=>'contacts','action' => 'index'));
} else {
//here we are setting a flash message for user for error if input are not
//validated as expected
$this->Session->setFlash('sorry we could add your record','error');
}
}
}
有關更多信息,您可以始終參考http://book.cakephp.org/2.0/en/models/callback-methods.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.