PHP - Validation function to return true | false and the message if false

I have a validation function that returns either true or false .
However, I want him to provide information on what the problem is, when it is.

Let's say the function is this:

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

Used as

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

I thought I could change it like this:

 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; } 

And use it as follows:

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

My question

  • Do I have for unexpected results with this?
  • Are there any better ways to achieve this?

PS Would make this community a wiki

+6
source share
3 answers

You're on the right track, but I would like to do it that way

 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); 
+11
source

You can use a Result object that encapsulates the returned data, message, and status.

i.e.

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

In your code:

 $result = new Result(true, 'some helpful message here', null); 
+2
source
 $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!'; 
+1
source

Source: https://habr.com/ru/post/886538/


All Articles