2015-11-07 72 views
2

我已經嘗試使用各種方法來設置使用codeigniter進行多選下拉列表的表單驗證,但無法正確設置規則。在這裏是我使用的代碼,好心幫助。附:我已經嘗試過在stackoverflow上建議的代碼,但徒勞無功。在codeigniter中的多選下拉列表的表單驗證

<select class="" name="travel_cat[]" multiple="multiple" id="travel_lst" data-placeholder="Select Travel Categories" style="width: 100%;"> 
        <option value="adventure">Adventure</option> 

         <option value="arts&culture">Arts & Culture</option> 

         <option value="events">Events</option> 

         <option value="backpacking">Backpacking</option> 

         <option value="beach_holidays">Beach Holidays</option> 

        <option value="budget_travel">Budget Travel</option> 

        <option value="city_travels">City Travels</option> 

        <option value="day_trips">Day Trips</option> 

        <option value="honeymoons">Honeymoons</option> 

        <option value="family_trips">Family Trips</option> 

        <option value="weekend_gateway">Weekend Gateway</option> 

        <option value="history&architecture">History & Architecture</option> 

        <option value="luxury">Luxury</option> 

        <option value="nature">Nature</option> 

        <option value="road_trips">Road Trips</option> 

        <option value="wildlife">Wildlife</option> 

        <option value="religious">Religious</option> 
       </select> 

$choice = $this->input->post("travel_cat"); 
    if(is_null($choice)) 
    { 
     $choice = array(); 
    } 
    $travel_cat = implode(',', $choice); 

表單驗證: -

$this->form_validation->set_rules('travel_cat', 'Travel Category', 'callback_check_default'); 

function check_default($array) 
{ 
    foreach($array as $element) 
    { 
     if($element == '0') 
     { 
      return FALSE; 
     } 
    } 
    return TRUE;   
} 
+0

多選框中沒有值'0'。它會一直返回你'真的' – Saty

+0

那麼我應該把什麼,而不是0? –

+0

您需要檢查'if($ element ==「」) { return FALSE; }' – Saty

回答

2

我更換了以下提到的代碼回調函數,它工作得很好。

function check_default() 
{ 
    $choice = $this->input->post("travel_cat"); 
    if(is_null($choice)) 
    { 
     $choice = array(); 
    } 
    $travel_cat = implode(',', $choice); 

    if($travel_cat != '') 
     return true; 
    else 
     return false; 
}