【问题标题】:CodeIgniter Input , and ValidationCodeIgniter 输入和验证
【发布时间】:2015-07-06 18:03:26
【问题描述】:

我正在使用 codeIgniter 2.2.2。 在控制器中,我捕获了输入,以便在验证失败时将其传递回视图,这样用户就不必从一开始就填写所有字段,我通过 $data 数组设置以下变量

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

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

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: fullname

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

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

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

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

【问题讨论】:

  • 你的观点是什么?如果可能,请使用视图和控制器编辑您的帖子
  • 如果可能,请提供您的控制器方法和视图!
  • 让我把那个代码放在我的 github 上,然后提供链接,请稍等。感谢您的时间 !我不能提供完整的代码,但我会提供这个视图的控制器和表单所在的视图。
  • 只有你的控制器方法和视图就够了,不是整个项目!
  • 亲爱的@ArkarAung,我添加了示例要点的链接。我知道我没有使用好的做法,但根据 PHP 和 CodeIgniter,代码仍然有效。 :)

标签: php codeigniter validation codeigniter-2


【解决方案1】:

试试这个。

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(不要重复自己)

编辑

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

希望对你有用。

【讨论】:

  • 感谢您提供有关如何以 DRY 方式进行操作的好技巧!但它仍然不起作用:(只有当我直接在视图中使用 $this->input->post('fullName') 时它才起作用。你将如何解决第二个问题?表单验证规则 alpha / alpha_numeric / alpha_dash none其中允许空格,是否有允许空格的规则?
  • 谢谢兄弟!实际上,我想看看 codeIgniter 中是否有一些内置方式而不是使用解决方法,但我认为遗憾的是没有内置方式。
  • 是的,只有三个内置方法,即 alpha、alpha-numeric 和 alpha-dash。需要创建自定义规则来实现 alpha-space。
【解决方案2】:

您错过了表单成功部分的$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');
    }
}

}

【讨论】:

    【解决方案3】:

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

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

    1. 捕获输入值并显示给用户的最佳方法是将输入的“值”属性设置为 set_value(),如 value="&lt;?= set_value('fieldName') ?&gt;",以防表单未成功提交并且您希望避免用户填写再次输入表单域。
    2. 我尝试将规则alpha_spaces 添加到 CodeIgniter 的核心(全名验证)功能,但拉取请求没有合并,所以我认为获得该功能的更好方法是使用方法 @arkar -aung 在他的回答中提到。

    当我今天看到它时,我当时使用的代码看起来很奇怪,它违反了最佳实践。看看我在 Quora 上关于how to better manage views in CodeIgniter 的回答。

    【讨论】:

      【解决方案4】:

      <!-- 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 -->	

      【讨论】:

        猜你喜欢
        • 2021-06-08
        • 1970-01-01
        • 1970-01-01
        • 2013-01-25
        • 2015-10-12
        • 2012-01-02
        • 2016-09-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多