【发布时间】:2013-10-19 22:09:01
【问题描述】:
我一直在关注 Envato 在 Tutplus 上的本教程:https://tutsplus.com/course/build-a-cms-in-codeigniter/。我正在验证登录表单的部分。我的问题是我不能在登录系统中使用我的表单验证规则。我的代码如下:
user_m.php
<?php
class User_M extends MY_Model {
public $rules = array( // I can't use this rules in my controller
'email' => array( // for email
'field' => 'email',
'label' => 'Email',
'rule' => 'trim|required|valid_email|xss_clean'
),
'password' => array( // for password
'field' => 'password',
'label' => 'Password',
'rule' => 'trim|required'
)
);
}
user.php
<?php
class User extends Admin_Controller {
public function __construct()
{
parent::__construct();
}
public function login()
{
// Set form
$rules = $this->user_m->rules; // get the value from user_m model and it works well
// this is not works. this is my problem
$this->form_validation->set_rules($rules);
// if we use this comment code then it works
//$this->form_validation->set_rules('email', 'Email', 'rim|required|valid_email|xss_clean');
// $this->form_validation->set_rules('password', 'Password', 'required');
// Process form
if ( $this->form_validation->run() == TRUE ) { // show the error msg if form problem occurs
// We can login and redirect
}
}
【问题讨论】:
-
它非常简单——你在你的模型中定义规则——但是你试图从控制器中调用它。我也做了那个教程,有一段时间我把我的模型称为“something_m”并认为它太酷了。事实上,我写了一篇文章——在写这篇文章时,我发现它实际上是一种糟糕的命名模式。所以我的建议是专门为模型命名,而控制器通常没有任何装饰。
-
建议把所有的表单验证都放在模型中,然后像这样调用它: if ( $this->user_m->validateUserForm() == False ){ // 再次显示表单 } else { // 转到另一个方法并让魔法发生 }
标签: php codeigniter validation