2011-04-23 59 views
6

我有它返回要麼truefalse驗證功能。
不過,我希望它提供以信息是什麼問題,當有一個。PHP - 驗證函數返回true | false,並且一條消息,如果假

假設的功能是這樣的:

function is_valid($val) { 
    $result = true; 
    if(rule_1_not_met) $result = false; 
    if(rule_2_not_met) $result = false; 
    return $result; 
} 

這是像這樣使用

$val = $_GET['some_param']; 
if(!is_valid($val)) $out .= 'Not so helpful feedback.'; 
... 

我想我可以改變這樣的:

function is_valid($val) { 
    $result = array(true, array()); 
    if(rule_1_not_met) $result[1][] = 'Reason 1'; 
    if(rule_2_not_met) $result[1][] = 'Reason 2'; 
    if(count($result[1]) > 0) $result[0] = false; 
    return $result; 
} 

並使用它像這樣:

$val = $_GET['some_param']; 
$validation_result = is_valid($val); 
if(!$validation_result[0]) $out .= implode('<br/>', $validation_result[1]); 
... 

我的問題是

  • 我是在爲這個意外的結果?
  • 是否有更好的方式來實現這一目標?

P.S.將使這個社區維基

+0

不要看到一個鏈接,使這個社會的維基。這是如何完成的? – 2011-04-23 15:27:45

+0

您可以將其標記爲主持人注意並寫一個簡短說明。但是,這不是一個社區維基問題。 – 2011-04-23 15:28:35

+0

@Felix Kling:我說過,因爲可能很難不接受多個答案。將等待,看看會發生什麼。 – 2011-04-23 15:33:12

回答

11

你是在正確的軌道,但我想這樣做這樣

function is_valid($val,&$mes) { 
    $result = true; 
    if(rule_1_not_met) { $mes[]='message one'; $result = false; } 
    if(rule_2_not_met) { $mes[]='Message two'; $result = false; } 
    return $result; 
} 

$mes=array(); 
if(isvalid($val,$mes) ===false) $out .= implode('<br/>', $mes); 
+0

這已超過多次打電話給'is_valid',這可能是有幫助的逐步建立消息的好處。 – 2011-06-19 14:13:05

+0

謝謝,這有助於調試。 – CrandellWS 2013-10-15 04:11:10

1
$reasons = array(); 
function is_valid($val) 
{ 
    global $reasons; 
    if (rule_1_not_met) $reasons[] = 'Reason 1'; 
    if (rule_2_not_met) $reasons[] = 'Reason 2'; 
    if (count($reasons) == 0) 
     return TRUE; 
    else 
     return FALSE; 
} 

if (!is_valid($condition)) 
{ 
    echo 'Was not valid for these reasons<br />'; 
    foreach($reasons as $reason) 
     echo $reason, '<br>'; 
} 
else 
    echo 'Is valid!'; 
2

你可以使用結果對象封裝返回數據,消息和狀態。

class Result($bResult, $sMessage, $mData) { 
    public function __construct() { 
     $this->bResult = $bResult; 
     $this->sMessage = $sMessage; 
     $this->mData = $mData; 
    } 
} 

在你的代碼:

$result = new Result(true, 'some helpful message here', null); 
+0

我喜歡你暗示這裏...但我不認爲這在野外,很多時候,@框架的建議是什麼,我看慣了,我甚至發現,使用該物品或示例方法...我今天只是一個Googletard嗎?或者有其他人使用你的方法嗎? – 2014-04-30 23:51:48

+1

Hi @CamdenS。 這是一個相當自定義的解決方案,我想 - 我的靈感來自一位前同事,他會使用這種結構移動數據。 – 2014-11-17 06:06:09

相關問題