Codeigniter - 在输入字段下面显示错误显示

Rji*_*jie 2 javascript php forms codeigniter-3

我试图在输入字段下面显示一个表单错误,但在我单击提交按钮后,它将重定向到另一个页面...

这是我的代码页控制器

<?php
    defined('BASEPATH') OR exit('No direct script access allowed');

    class Pages extends CI_Controller{

        public function view($page = 'home'){
            if(!file_exists(APPPATH.'views/pages/'.$page.'.php')){
                show_404();
            }
            $data['title'] = ucfirst($page);

            $this->load->view('template/header');
            $this->load->view('pages/'.$page);
            $this->load->view('template/footer');
        }

        public function login(){
            echo $this->input->POST('username');
        }

        public function registercheck(){

            echo $this->input->POST('username');
            echo $this->input->POST('pwd');
            echo $this->input->POST('pwd2');
            echo $this->input->POST('fname');
            echo $this->input->POST('position');
            echo $this->input->POST('contactnumber');

            $this->form_validation->set_rules('username', 'USERNAME', 'required|max_lenght[20]');
            $this->form_validation->set_rules('pwd', 'USERNAME', 'required|max_lenght[20]');
            $this->form_validation->set_rules('pwd2', 'UPPERCASE', 'required|max_lenght[20]');
            $this->form_validation->set_rules('fname', 'USERNAME', 'required|max_lenght[20]');
            $this->form_validation->set_rules('position', 'USERNAME', 'required|max_lenght[20]');
            $this->form_validation->set_rules('contactnumber', 'USERNAME', 'required|max_lenght[20]');

            if($this->form_validation->run() == false){
                $this->load->view('pages/register');
            } else{
                echo 'register ok';
            }                   
        }
    }
?>
Run Code Online (Sandbox Code Playgroud)

这是我的观点/ pages/register.php

<form action="<?php echo base_url(); ?>pages/registercheck" method="post">
    <input type="text" class="form-control" id="username" name="username" value="<?php echo set_value('username'); ?>" >
    <?php if (form_error('username')) { ?>
        <span class="help-block"><?php echo form_error('username');  ?> </span>
    <?php } ?>

    <input type="text" class="form-control" id="username" name="username" value="<?php echo set_value('username'); ?>" >
    <?php  if (form_error('username')) { ?>
        <span class="help-block"><?php echo form_error('username');  ?> </span>
    <?php } ?>
</form>
Run Code Online (Sandbox Code Playgroud)

请帮帮我..我做错了什么?

先感谢您!

Gal*_*man 5

你是在正确的方向.但要实现所需功能,您应该这样做:

表单和输入验证应该在同一页面(控制器)中.在你的例子中,两者都应该在register.php.

这个基本的伪代码可以做到这一点:

On register page controller:
    If method == get:
        Display register form.
    If method == post:
        Check the form data:
        If errors exists:
            display register page with error.
        else:
            redirect to ....
Run Code Online (Sandbox Code Playgroud)

祝好运!