2013-01-22 49 views
2

我的表單中有3個字段 - 讓我們說A,B和C.我想設置驗證規則,如果字段A和B爲空,則需要C。否則,需要A和B.如何在CodeIgniter中使用表單驗證爲set_rules()編寫條件?

我查了一些關於這個的材料,基本上我發現我可以使用回調函數,但是我對CodeIgniter有點新意,我不能完全弄清楚寫出來的語法。

+0

想知道如果C填寫或不填寫A和B是必需的 – umefarooq

回答

3

很簡單

function index() 
{ 
    $this->load->helper(array('form', 'url')); 

    $this->load->library('form_validation'); 

    $post_data = $this->input->post(); 

    $this->form_validation->set_rules('A', 'FieldA', 'required'); 
    $this->form_validation->set_rules('B', 'FieldB', 'required'); 

    if(!isset($post_data['A']) AND !isset($post_data['B'])) 
    { 
     $this->form_validation->set_rules('C', 'FieldC', 'required'); 
    } 


    if ($this->form_validation->run() == FALSE) 
    { 
     $this->load->view('myform'); 
    } 
    else 
    { 
     $this->load->view('success'); 
    } 
} 
6

回調是處理這種最徹底的方法:

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

class YourController extends CI_Controller { 

    public function save() 
    { 
     //.... Your controller method called on submit 

     $this->load->library('form_validation'); 

     // Build validation rules array 
     $validation_rules = array(
           array(
            'field' => 'A', 
            'label' => 'Field A', 
            'rules' => 'trim|xss_clean' 
            ), 
           array(
            'field' => 'B', 
            'label' => 'Field B', 
            'rules' => 'trim|xss_clean' 
            ), 
           array(
            'field' => 'C', 
            'label' => 'Field C', 
            'rules' => 'trim|xss_clean|callback_required_inputs' 
            ) 
           ); 
     $this->form_validation->set_rules($validation_rules); 
     $valid = $this->form_validation->run(); 

     // Handle $valid success (true) or failure (false) 

    } 


    public function required_inputs() 
    { 
     if(! $this->input->post('A') AND ! $this->input->post('B') AND $this->input->post('C')) 
     { 
      $this->form_validation->set_message('required_inputs', 'Either A and B are required, or C.'); 
      return FALSE; 
     } 

     return TRUE; 
    } 
} 
1

你能做到這樣,如下圖所示,如果您將set_rules在if結構當您嘗試使用表單助手重新填充時,您可能會遇到問題。

function index() 
{ 
    $required=''; 
    if(isset($this->input->post('A')) && isset($this->input->post('B'))) 
    { 
     $required='required'; 
    } 
    $this->form_validation->set_rules('A', 'FieldA', 'required'); 
    $this->form_validation->set_rules('B', 'FieldB', 'required'); 
    $this->form_validation->set_rules('C', 'FieldC', $required); 

    if ($this->form_validation->run() == FALSE) 
    { 
     $this->load->view('myform'); 
    } 
    else 
    { 
     $this->load->view('success'); 
    } 
}