【发布时间】:2016-10-23 18:39:09
【问题描述】:
您好,希望您能帮我解决这个问题。 我在这个问题上看到了许多相同的问题,但没有一个对我有用。
我正在使用 Codeigniter 2.2.2 并尝试在模型中创建表单验证,以便多个控制器可以访问它。表单验证无法在模型中声明的自定义回调上正确返回。
// in Model
function validateErrors() {
$rules = array(
array('field'=>'username', 'label'=>'User', 'rules'=>'trim|required|callback_userPrefix'),
array('field'=>'password', 'label'=>'Password', 'rules'=>'trim|required|callback_passwordNotEmpty'),
);
$this->load->library('form_validation');
$this->form_validation->set_rules($rules);
if ($this->form_validation->run() == FALSE) {
$errors = array();
foreach ($rules as $r)
$errors[$r['field']] = $this->form_validation->error($r['field']);
return $errors;
}
return false;
}
public function userPrefix() {
$find = 'user_';
if (strpos($this->input->post('username'), $find) != 0) {
$this->form_validation->set_message('userPrefix', 'Username not allowed.');
return false;
}
return true;
}
public function passwordNotEmpty() {
// not the actual callback just an example
if (empty($this->input->post('password'))) {
$this->form_validation->set_message('passwordNotEmpty', 'Password cannot be blank.');
return false;
}
return true;
}
这样就可以在Controller中访问了:
// in Controller
if ($this->input->post()) {
$this->load->model('ModelName','model1', true);
$validation_errors = $this->model1->validateErrors();
if ($validation_errors === false) {
// continue saving record
} else {
print_r($validation_errors); exit;
}
}
我想为每个用户登录创建表单验证。但是由于多个控制器使用相同的验证,我在模型中声明了验证及其自定义回调以最小化控制器中的编码长度(希望最小化)。
另外,this answer 说您可以在模型中进行表单验证(还显示模型中声明的回调应该有效)。我试过了,但对我不起作用。
任何人都可以帮助我吗?非常感谢!
【问题讨论】:
-
也许这是升级到 Codeigniter 3 的原因?升级有巨大的优势,而且没有太多的重大变化。然后你可以在你的模型中使用 callable ,比如:codeigniter.com/user_guide/libraries/…
-
@cartalot 这是否意味着它无法完成?我无法升级到 v3,因为我只能访问我当前公司系统上的某些模块
-
与我们分享您的 html,然后更容易弄清楚发生了什么。
-
你在你的 CI 中使用 HMVC 吗? (我的意思是,模块化 CI)?如果是这样,您必须欺骗一下 Form_validation 类....
标签: php forms codeigniter validation