PHP – Validation function to return true|false, AND a message if false

Issue

I have a validation function which returns either true or false.
However, I want it to provide info as to what the problem is, when there is one.

Let’s say the function is like this:

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

Which is used like this

$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 like this:

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

My question is

  • Am I in, for unexpected results with this?
  • Are there better ways to achieve this?

P.S. Would make this community wiki

Solution

You are in the right track but I would like to do this in this 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);

Answered By – Shakti Singh

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published