CodeIgniter 输入和验证

CodeIgniter Input , and Validation

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

$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 甚至不允许 spaces,在这种情况下我需要,因为表单字段是全名,其中必须有一个 space 例如 "Albert Einstein".

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

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

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

}

试试这个。

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

编辑

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

希望对你有用。

很久以后我才遇到这个问题(我自己的问题)。我刚开始学习CodeIgniter的时候问过这个问题。

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

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

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

的回答

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