我正在为Codeigniter中的用户开发登录功能。
这是我的用户控制器的一部分:
public function login() {
$name = $this->input->post('username');
$pass = $this->input->post('pass');
$this->form_validation->set_rules('username', 'Användarnamn', 'required');
$this->form_validation->set_rules('pass', 'Lösenord', 'required');
//Username or password not given
if ($this->form_validation->run() == false) {
$succesful = false;
}
else {
//Form itself validates (Username and password is given)
//Check if username and password matches against some user in the database
$um = new Usermodel();
$um->setUsername($name);
$um->setPassword($pass);
//True if account exists or false if it does not
$succesful = $um->accountExists();
}
$data = array();
$succesful = false; //TEMP
if ($succesful === false) {
$data['error'] = 'groovy';
$this->form_validation->set_message('username', 'groovy' );
}
//Show template
$data['loginform'] = $this->loginform();
$data['registerform'] = $this->registerform();
$this->load->view('home', $data);
}
我的观点(主页)中的片段看起来像:
<?php
echo validation_errors(); //Show errors if they occur on submit
if (isset($error)) {
echo $error;
}
if (isset($loginform)) {
echo $loginform;
}
if (isset($registerform)) {
echo $registerform;
}
?>
当用户点击登录表单上的提交时,将调用login()
函数。如果登录因数据库中的用户匹配而失败,则会回显单词groovy。
有没有办法使用$data['error'] = 'groovy'
来实现没有?
我想要做的是替换:
echo validation_errors(); //Show errors if they occur on submit
if (isset($error)) {
echo $error;
}
与
echo validation_errors(); //Show errors if they occur on submit
在我看来(validation_errors()
应该返回groovy)
如果我理解正确,这只是在输入用户名不正确时(基于规则)指定值。
$this->form_validation->set_message('username', 'groovy' );
答案 0 :(得分:1)
扩展表单验证类并添加自定义函数以将消息添加到错误数组(validation_errors()
获取其消息的位置);
库/ MY_Form_validation.php
class MY_Form_validation extends CI_Form_validation
{
public function add_error($field, $message)
{
if ( ! isset($this->_error_array[$field]))
{
$this->_error_array[$field] = $message;
}
return;
}
}
控制器:
$succesful = false; //TEMP
if ($succesful === false) {
$this->form_validation->add_error('username', 'Username is groovy!');
}