2013-05-05 53 views
2

可能是重複的。但我無法在谷歌上找到任何東西,所以我們去。使用codeigniter表單驗證庫。驗證陣列不是從郵政

我有一個表單提交數據。這些數據會進一步處理並將其分解爲變量。

例如

我的表單提交<input name='cmd' value='create -u [email protected] -p password'/>

,所以我接受這樣的職位,並將其分成

[email protected] 
$password=password 

現在我想驗證這些變量,因爲form_validation庫。已經在那裏,爲什麼不使用它!我知道我可以使用preg_match。但我認爲我沒有必要重新發明了什麼已經存在,一個

$this->form_validation->set_rules($username, 'username', 'required|xss_clean'); 
$this->form_validation->set_rules($password, 'username', 'required|xss_clean'); 

將是一個美麗的方法。

有沒有一種方法可以調整CI表單驗證接受變量而不是field_name?可能是一個幫手功能,對於這件事情會很好。甚至可以使用$$變量來爲id []驗證等規則的變量的名稱。

非常感謝,我希望我能很好地解釋我的問題。

+2

我認爲你在你的問題上得到了答案,form_validation與$ _POST數組一起工作,在應用這種驗證之前進行分割:'$ _POST ['username'] ='username @ demo.com''。行動'$ this-> form_validation-> set_rules('username','username','required | xss_clean')'將會正確處理它 – 2013-05-05 11:56:33

+0

好吧,它只是不適合我砍$ _POST,我正在尋求更多優雅的解決方案!,但以任何方式:) – Zalaboza 2013-05-05 20:05:59

+0

CI 3.0允許您定義自己的數據數組進行驗證。您可以在[Github](https://github.com/EllisLab/CodeIgniter)上獲取代碼,並自行擴展/替換驗證庫,或完全使用3.0(由您自擔風險)。 – 2013-05-05 23:10:45

回答

0

有2種方式來完成你所需要的,一個是定義你的輸入字段並做分裂在客戶端,如:

<form method="post"> 
    <input id="cmd" value="<?php if (set_value('username')) : ?>create -u <?=set_value('username')?> -p <?=set_value('password')?><?php endif; ?>"/> 
    <input type="hidden" name="username" value="<?=set_value('username')?>" /> 
    <input type="hidden" name="password" value="<?=set_value('password')?>" /> 
</form> 
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"/> 
<script type="text/javascript"> 
$(function() { 
    $('#cmd').change(function() { 
     var matches = $(this).val().match(/create -u ([^\b]+) -p ([^\b]+)\]/); 
     $('input[name=username]').val(matches[1]); 
     $('input[name=password]').val(matches[2]); 
    }); 
}); 
</script> 

,或者你只是用像一個回調確認:

<form method="post"> 
    <input name="cmd" value="<?=set_value('cmd')?>"/> 
</form> 

$this->form_validation->set_rules('cmd', 'Command', 'required|callback_validate_cmd'); 

function validate_cmd($cmd) 
{ 
    if ($cmd) { 
     list($username, $password) = split_cmd($cmd); 
     $this->load->helper('security'); 
     if (! xss_clean($username)) { 
      $this->form_validation->set_message(__FUNCTION__, 'username_not_secure'); 
      return FALSE; 
     } elseif (! xss_clean($password)) { 
      $this->form_validation->set_message(__FUNCTION__, 'password_not_secure');ç 
      return FALSE; 
     } 
    } 
    return TRUE; 
}