在codeigniter中扩展表单验证规则

时间:2015-04-30 10:58:40

标签: codeigniter extend

enter image description here我有一个包含两个字段的表单

<input type="text" name="total_plots" value="" placeholder="Enter Total plots"  />
<input type="text" name="available_plots" value="" placeholder="Enter Available Plots "  />

可用情节&#34; available_plots&#34;字段值应小于总图&#34; total_plots&#34;字段值

我不想写回调。我想扩展表单验证规则。

如何?

MY_Form_validation

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

    class MY_Form_validation extends CI_Form_validation {

        public function __construct()
        {
            parent::__construct();
            $this->CI =& get_instance();
        }


      public function check_avail($str)
    {
        $this->CI->form_validation->set_message('check_avail', 'Available plot should be less than Total plot.');
        $total_plots = $this->CI->input->post('total_plots');

        //echo '------'.$total_plots;
        //echo '------'.$str;

        if($str > $total_plots){ 
            return false;
        }
  }

 }  // class

我在config

中编写了规则
<?php

$config['plot_settings'] = array(

        array(
                'field' => 'total_plots',
                'label' => 'Total Plots',
                'rules' => 'trim|xss_clean'
        ),
        array(
                'field' => 'available_plots',
                'label' => 'Available Plots',
                'rules' => 'trim|xss_clean|check_avail'
        )


);

?>

控制器

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

class Plot extends CI_Controller {


    public function __construct()
    {
        parent::__construct();
        $this->load->library('Admin_layout');
        $this->load->model('admin/plot_model');
        $this->config->load('plot_rules');
        $this->output->enable_profiler(TRUE);
        $this->new_name='';
    }


    public function add(){


     $this->form_validation->set_rules($this->config->item('plot_settings'));
     $this->form_validation->set_error_delimiters('<p><b>', '</b></p>');


      if ($this->form_validation->run('submit') == FALSE ) 
      {

            $this->admin_layout->set_title('Post Plot');  
            $this->admin_layout->view('admin/post_plot');
      } 


    }//add
 }

1 个答案:

答案 0 :(得分:1)

我认为您可以在不编写回调或扩展验证规则的情况下执行此操作。

CI已提供验证规则以检查less_than值。

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

$this->form_validation->set_rules('available_plots', 'Available Plots', "less_than[$total_plots]");

它应该有用。