在 codeigniter 中扩展表单验证规则

Extending form validation rule in codeigniter

我有一个包含两个字段的表单

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

可用地块"available_plots" 字段值应小于总地块"total_plots" 字段值

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

如何?

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
 }

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

CI 已经提供了一个验证规则来检查 less_than 值。

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

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

应该可以。