CodeIgniter输入和验证

时间:2015-04-28 04:00:57

标签: php codeigniter validation codeigniter-2

我正在使用codeIgniter 2.2.2。 在Controller中我捕获了输入,以便在验证失败的情况下将其传递回视图,这样用户就不会被迫从开始填充所有字段,我通过$ data array设置以下变量

$data['fullname'] = $this->input->post('fullName');

但是当用户首先访问表单时,它会给出如下错误。

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: fullname

如果我在视图中直接使用$this->input->post('fullName');而不是触发错误,但我想从Controller传递它。

第二个问题是当我将此输入的表单验证规则设置为$this->form_validation->set_rules('fullName', 'Full Name', 'required|alpha');时,验证规则alpha甚至不允许在这种情况下我需要的空格,因为表单字段是全名,必须有一个空间,例如,"阿尔伯特爱因斯坦"。

我可以通过将两个不同的表单输入字段设置为" First Name"来解决这个问题。和#34;姓氏",但我不喜欢这样,因为我认为一个框架应该让我的生活更轻松而不是更难。

这是一个示例代码示例,它将触发我说的错误。 Example Gist

4 个答案:

答案 0 :(得分:2)

试试这个。

public function contact() {
    $this->load->library("session");
    $data['message'] = $this->session->flashdata("message");
    $data['fullname'] = $this->session->flashdata("fullname");
    $this->load->view('site_header');
    $this->load->view('site_nav');
    $this->load->view('content_contact', $data);
    $this->load->view('site_footer');
} 

public function send_email() {
    $this->load->library('form_validation');
    $this->form_validation->set_rules('fullName', 'Full Name', 'required|callback_fullname_check');
    $this->form_validation->set_rules('email', 'Email Address', 'required|valid_email');
    $this->form_validation->set_rules('message', 'Message', 'required');

    if ($this->form_validation->run() == false) {
        $this->session->set_flashdata("message", validation_errors());
        $this->session->set_flashdata("fullname", $this->input->post('fullName'));
    } else {
        $this->session->set_flashdata("message", "The email has successfully been sent!");
    }
    redirect("site/contact");
}

public function fullname_check($str) {
    if (! preg_match("/^([a-z0-9 ])+$/i", $str)) {
        $this->form_validation->set_message('fullname_check', 'The %s field can only be alpha numeric');
        return FALSE;
    } else {
        return TRUE;
    }
}

请避免重复加载视图 DRY (不要重复自己)

修改

尝试使用自定义验证规则来实现带空格的字母数字字符串。

希望它对你有用。

答案 1 :(得分:1)

您错过了表单成功部分的$data['fullname'] = "",但是您尝试将代码加倍,尽可能让它更精益。

我该怎么做。

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

class Contact extends CI_Controller {

  public function index() {

    $this->load->library('form_validation');
    // Double check spelling of set rules make sure matches the input on the view name="" area
    $this->form_validation->set_rules('fullname', 'Full Name', 'required'); // Removed |alpha no need I think
    $this->form_validation->set_rules('email', 'Email Address', 'required|valid_email');
    $this->form_validation->set_rules('message', 'Message', 'required');

    $fullname = $this->input->post('fullname');

    if (isset($fullname)) {
        $data['fullname'] = $fullname;
    } else {
        $data['fullname'] = "";
    }

    $data['message'] = "";

    if ($this->form_validation->run() == false) {

        $this->load->view('site_header');
        $this->load->view('site_nav');
        $this->load->view('content_contact', $data);
        $this->load->view('site_footer');

    } else {

        $data['message'] = "The email has successfully been sent!";
        $this->load->view('site_header');
        $this->load->view('site_nav');
        $this->load->view('content_contact', $data);
        $this->load->view('site_footer');
    }
  }
}

查看:注意可能需要设置一些路线。

<form action="<?php echo base_url('contact');?>" method="post">
<input type="text" name="fullname" value="<?php echo $fullname;?>" placeholder=""/>
</form>

您的代码

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

class Site extends CI_Controller {

public function contact() {
    $data['message'] = '';

    $this->load->view('site_header');
    $this->load->view('site_nav');
    $this->load->view('content_contact', $data);
    $this->load->view('site_footer');
}

public function send_email() {
    $this->load->library('form_validation');

    $this->form_validation->set_rules('fullName', 'Full Name', 'required|alpha');
    $this->form_validation->set_rules('email', 'Email Address', 'required|valid_email');
    $this->form_validation->set_rules('message', 'Message', 'required');

    if ($this->form_validation->run() == false) {
        $data['message'] = '';

        $data['fullname'] = $this->input->post('fullName');

        $this->load->view('site_header');
        $this->load->view('site_nav');
        $this->load->view('content_contact', $data);
        $this->load->view('site_footer');
    } else {
        $data['fullname'] = "";

        $data['message'] = 'The email has successfully been sent!';

        $this->load->view('site_header');
        $this->load->view('site_nav');
        $this->load->view('content_contact', $data);
        $this->load->view('site_footer');
    }
}

}

答案 2 :(得分:0)

经过很长一段时间,我遇到了这个问题(我自己的问题)。当我开始学习CodeIgniter时,我问了这个问题。

我在问题中询问了两件事,以下是这两个(当时)问题的最佳答案。

  1. 捕获输入值并向用户显示的最佳方法是将输入的'value'属性设置为set_value(),如value="<?= set_value('fieldName') ?>",以防表单未成功提交并且您想要保存用户从填写表格字段再次。
  2. 我尝试向CodeIgniter的核心添加规则alpha_spaces以获取(全名验证)功能,但拉取请求未合并,所以我认为获得该功能的更好方法是使用该方法@ arkar-aung在他的回答中提到。
  3. 当我今天看到它时,我使用的代码看起来很奇怪,它违背了最佳实践。请看Quora关于how to better manage views in CodeIgniter的答案。

答案 3 :(得分:0)

&#13;
&#13;
<!-- form validation -->
	<!-- form validation controller-->	
		class Securities_Controller extends CI_Controller {
		    /**
		     * load the add security page
		     */
		    public function index() {
		        $this->load->model('securities/Security_Model');
		        $data['security'] = $this->Security_Model->get_new();
		        $this->load->view('securites_view/index', $data);
		    }

		    public function add() {
		        echo 'add';
		        $this->load->model('securities/Security_Model');
		        $data['security'] = $this->Security_Model->get_new(); //create empty fields
		        $rules = $this->Security_Model->rules;
		        $this->form_validation->set_rules($rules);
		        if ($this->form_validation->run() == TRUE) {
		            
		        }
		        $this->load->view('securites_view/index', $data);
		    }
		}
	<!-- //form validation controller-->
	<!-- form validation model-->
		class Security_Model extends CI_Model {
		    //put your code here
		    function __construct() {
		        parent::__construct();
		    }
		    //validation rules
		    public $rules = array(
		        'cdsaccid' => array(
		            'field' => 'cdsaccid',
		            'label' => 'CDS Account',
		            'rules' => 'trim|required'
		        ),
		        'comid' => array(
		            'field' => 'comid',
		            'label' => 'Company Name',
		            'rules' => 'trim|required'
		        )
		    );
		    //the standered class for security 
		    function get_new() { 
		        $Security = new stdClass();
		        $Security->cdsaccid = '';
		        $Security->comid = '';
		        return $Security;
		    }
		      public function array_from_post($fields) {
		        $data = array();
		        foreach ($fields as $field) {
		            $data[$field] = $this->input->post($field);
		        }
		        return $data;
		    }
		}
	<!-- //form validation model-->
	<!-- form validation view-->
		<?php echo form_open('Securities_Controller/add') ?>
                                   <?php echo validation_errors();?>
                                        <div class="form-group">
                                            <label for="exampleInputEmail1">CDS Acc</label>
                                            <input type="text" name="cdsaccid" class="form-control" value="<?=set_value('cdsaccid', $security->cdsaccid);?>" >
                                        </div>
                                        <div class="form-group">
                                            <label for="exampleInputPassword1">Company</label>
                                            <input type="text" name="comid" class="form-control" id="exampleInputPassword1">
                                        </div>
                                        <button type="submit" class="btn btn-default">Submit</button>
        <?php echo form_close() ?>
	<!-- //form validation view-->
<!-- //form validation -->	
&#13;
&#13;
&#13;