Codeigniter在表单验证后重新格式化POST数据

时间:2015-05-12 15:22:44

标签: php forms codeigniter

我遇到了问题,我无法想象这是怎么回事。所以我运行form_validation来验证我的表单输入。之后,$_POST['user_name']变为数组而不是字符串。

$this->form_validation->set_rules('user_name', 'Vartotojo vardas',
        'trim|required|min_length[5]|max_length[30]|alpha_dash|callback_checkUserNameUnique');
    $this->form_validation->set_rules('email', 'El. pašto adresas',
        'trim|required|valid_email|callback_checkEmailUnique');
    $this->form_validation->set_rules('password', 'Slaptažodis',
        'trim|required|min_length[5]|max_length[60]');
    $this->form_validation->set_rules('password_2', 'Slaptažodžio pakartojimas',
        'trim|required|min_length[5]|max_length[60]|matches[password]');
    $this->form_validation->set_rules('phone_number', 'Telefono numeris',
        'trim|required|callback_checkIfPhoneGood');

    $this->setFormMessages();


    if ( $this->form_validation->run() == false ) {
        $data['json'] = array(
            'failed' => true,
            'errors' => $this->form_validation->error_array()
        );
    } else {
        print_r($_POST['user_name']);
        print_r($this->input->post('user_name', true));
    }

在启动$this->form_validation->run()并打印$_POST['user_name']之前返回字符串,在$this->form_validation->run()之后返回空数组。

有什么想法吗?

编辑:

my checkUserNameUnique方法:

function checkUserNameUnique($userName)
{
    return $this->cache->model('system_model', '_getCustomTableData', array(
        'users', array(array('user_name' => strtolower($userName))), 'id DESC', FALSE, 1
    ), CACHE_USER_CHECK_INFO_TIME);
}

1 个答案:

答案 0 :(得分:1)

_getCustomTableData返回一个数组,所以改变你的回调函数:

function checkUserNameUnique($userName)
{
    if (empty($this->cache->model('system_model', '_getCustomTableData', array(
        'users', array(array('user_name' => strtolower($userName))), 'id DESC', FALSE, 1
        ), CACHE_USER_CHECK_INFO_TIME)))
    {
        return TRUE;
    }
    else
    {
        $this->form_validation->set_message('username_unique', 'The %s field must be unique.');
        return FALSE;
    }    
}

表单验证还支持检查唯一性:

$this->form_validation->set_rules('user_name', 'Vartotojo vardas',
    'trim|required|min_length[5]|max_length[30]|alpha_dash|is_unique[users.user_name]');