如何在codeigniter中的每个字段上显示错误

时间:2016-10-03 18:22:11

标签: php codeigniter

$this->form_validation->set_rules('username', 'User Name', 'required|min_length[4]|is_unique[users.username]');
$this->form_validation->set_rules('fname', 'Full Name', 'required|min_length[4]');
$this->form_validation->set_rules('user_password', 'Password', 'required|matches[confirm_password]');
$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'required');
$this->form_validation->set_rules('cname', 'College Name', 'required');
$this->form_validation->set_rules('dob', 'Date of Birth', 'required|callback_valid_date');
$this->form_validation->set_rules('addr', 'Address', 'required');
$this->form_validation->set_rules('contact', 'Contact', 'required|min_length[10]|max_length[10]');
$this->form_validation->set_rules('education', 'Education', 'required');
$this->form_validation->set_rules('user_email', 'Email', 'required|valid_email|is_unique[users.email]');
if ($this->form_validation->run() == FALSE)
    {
        $this->session->set_flashdata('result', validation_errors());
        redirect('login/register');

    }
    else
    {

      $rr = $this->user->register_user();
      $this->session->set_flashdata('result', $rr);
    redirect('login/register');
    }
}

基本上使用$ this-> session-> flashdata(“result”);显示结果,但我希望每个文件分别验证我已经尝试过form_error(“字段名称”);但它无法显示空结果

1 个答案:

答案 0 :(得分:0)

如果存在任何验证错误,请尝试加载相同的表单,而不是重定向。

在控制器页面中。

function your_function(){
        // load form helper
        $this->load->helper(array('form', 'url'));
        // load form validation library 
        $this->load->library('form_validation');
        // validation rules
        $this->form_validation->set_rules('username', 'User Name', 'required|min_length[4]|is_unique[users.username]');
        $this->form_validation->set_rules('fname', 'Full Name', 'required|min_length[4]');
                // check form for validations
                if ($this->form_validation->run() == FALSE){
                        // load the same form/view
                        $this->load->view('myform');
                } else{
                  // redirect to success page
               }
}

在视图页面中:可以使用form_error()函数在每个表单字段旁边显示错误消息

<?php echo form_error('username'); ?>
<input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" />

<?php echo form_error('fname'); ?>
<input type="text" name="fname" value="<?php echo set_value('fname'); ?>" size="50" />